Home | History | Annotate | Download | only in btm
      1 /******************************************************************************
      2  *
      3  *  Copyright (C) 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 for the Bluetooth Security Manager
     22  *
     23  ******************************************************************************/
     24 
     25 #define LOG_TAG "bt_btm_sec"
     26 
     27 #include <stdarg.h>
     28 #include <stdio.h>
     29 #include <string.h>
     30 
     31 #include "device/include/controller.h"
     32 #include "osi/include/log.h"
     33 #include "osi/include/osi.h"
     34 #include "osi/include/time.h"
     35 
     36 #include "bt_types.h"
     37 #include "bt_utils.h"
     38 #include "btm_int.h"
     39 #include "btu.h"
     40 #include "hcimsgs.h"
     41 #include "l2c_int.h"
     42 
     43 #include "gatt_int.h"
     44 
     45 #define BTM_SEC_MAX_COLLISION_DELAY (5000)
     46 
     47 #ifdef APPL_AUTH_WRITE_EXCEPTION
     48 bool(APPL_AUTH_WRITE_EXCEPTION)(const RawAddress& bd_addr);
     49 #endif
     50 
     51 /*******************************************************************************
     52  *             L O C A L    F U N C T I O N     P R O T O T Y P E S            *
     53  ******************************************************************************/
     54 tBTM_SEC_SERV_REC* btm_sec_find_first_serv(bool is_originator, uint16_t psm);
     55 static tBTM_SEC_SERV_REC* btm_sec_find_next_serv(tBTM_SEC_SERV_REC* p_cur);
     56 static tBTM_SEC_SERV_REC* btm_sec_find_mx_serv(uint8_t is_originator,
     57                                                uint16_t psm,
     58                                                uint32_t mx_proto_id,
     59                                                uint32_t mx_chan_id);
     60 
     61 static tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec);
     62 static bool btm_sec_start_get_name(tBTM_SEC_DEV_REC* p_dev_rec);
     63 static void btm_sec_start_authentication(tBTM_SEC_DEV_REC* p_dev_rec);
     64 static void btm_sec_start_encryption(tBTM_SEC_DEV_REC* p_dev_rec);
     65 static void btm_sec_collision_timeout(void* data);
     66 static void btm_restore_mode(void);
     67 static void btm_sec_pairing_timeout(void* data);
     68 static tBTM_STATUS btm_sec_dd_create_conn(tBTM_SEC_DEV_REC* p_dev_rec);
     69 static void btm_sec_change_pairing_state(tBTM_PAIRING_STATE new_state);
     70 
     71 static const char* btm_pair_state_descr(tBTM_PAIRING_STATE state);
     72 
     73 static void btm_sec_check_pending_reqs(void);
     74 static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm,
     75                                      bool is_orig, uint32_t mx_proto_id,
     76                                      uint32_t mx_chan_id,
     77                                      tBTM_SEC_CALLBACK* p_callback,
     78                                      void* p_ref_data);
     79 static void btm_sec_bond_cancel_complete(void);
     80 static void btm_send_link_key_notif(tBTM_SEC_DEV_REC* p_dev_rec);
     81 static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec);
     82 
     83 static uint8_t btm_sec_start_authorization(tBTM_SEC_DEV_REC* p_dev_rec);
     84 bool btm_sec_are_all_trusted(uint32_t p_mask[]);
     85 
     86 static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec,
     87                                                uint8_t reason,
     88                                                uint16_t conn_handle);
     89 uint8_t btm_sec_start_role_switch(tBTM_SEC_DEV_REC* p_dev_rec);
     90 tBTM_SEC_DEV_REC* btm_sec_find_dev_by_sec_state(uint8_t state);
     91 
     92 static bool btm_sec_set_security_level(CONNECTION_TYPE conn_type,
     93                                        const char* p_name, uint8_t service_id,
     94                                        uint16_t sec_level, uint16_t psm,
     95                                        uint32_t mx_proto_id,
     96                                        uint32_t mx_chan_id);
     97 
     98 static bool btm_dev_authenticated(tBTM_SEC_DEV_REC* p_dev_rec);
     99 static bool btm_dev_encrypted(tBTM_SEC_DEV_REC* p_dev_rec);
    100 static bool btm_dev_authorized(tBTM_SEC_DEV_REC* p_dev_rec);
    101 static bool btm_serv_trusted(tBTM_SEC_DEV_REC* p_dev_rec,
    102                              tBTM_SEC_SERV_REC* p_serv_rec);
    103 static bool btm_sec_is_serv_level0(uint16_t psm);
    104 static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security,
    105                                               bool is_originator);
    106 
    107 static bool btm_sec_queue_encrypt_request(const RawAddress& bd_addr,
    108                                           tBT_TRANSPORT transport,
    109                                           tBTM_SEC_CALLBACK* p_callback,
    110                                           void* p_ref_data,
    111                                           tBTM_BLE_SEC_ACT sec_act);
    112 static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec,
    113                                           tBT_TRANSPORT transport,
    114                                           uint8_t encr_enable);
    115 
    116 static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec);
    117 static bool btm_sec_is_master(tBTM_SEC_DEV_REC* p_dev_rec);
    118 
    119 /* true - authenticated link key is possible */
    120 static const bool btm_sec_io_map[BTM_IO_CAP_MAX][BTM_IO_CAP_MAX] = {
    121     /*   OUT,    IO,     IN,     NONE */
    122     /* OUT  */ {false, false, true, false},
    123     /* IO   */ {false, true, true, false},
    124     /* IN   */ {true, true, true, false},
    125     /* NONE */ {false, false, false, false}};
    126 /*  BTM_IO_CAP_OUT      0   DisplayOnly */
    127 /*  BTM_IO_CAP_IO       1   DisplayYesNo */
    128 /*  BTM_IO_CAP_IN       2   KeyboardOnly */
    129 /*  BTM_IO_CAP_NONE     3   NoInputNoOutput */
    130 
    131 /*******************************************************************************
    132  *
    133  * Function         btm_dev_authenticated
    134  *
    135  * Description      check device is authenticated
    136  *
    137  * Returns          bool    true or false
    138  *
    139  ******************************************************************************/
    140 static bool btm_dev_authenticated(tBTM_SEC_DEV_REC* p_dev_rec) {
    141   if (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED) {
    142     return (true);
    143   }
    144   return (false);
    145 }
    146 
    147 /*******************************************************************************
    148  *
    149  * Function         btm_dev_encrypted
    150  *
    151  * Description      check device is encrypted
    152  *
    153  * Returns          bool    true or false
    154  *
    155  ******************************************************************************/
    156 static bool btm_dev_encrypted(tBTM_SEC_DEV_REC* p_dev_rec) {
    157   if (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) {
    158     return (true);
    159   }
    160   return (false);
    161 }
    162 
    163 /*******************************************************************************
    164  *
    165  * Function         btm_dev_authorized
    166  *
    167  * Description      check device is authorized
    168  *
    169  * Returns          bool    true or false
    170  *
    171  ******************************************************************************/
    172 static bool btm_dev_authorized(tBTM_SEC_DEV_REC* p_dev_rec) {
    173   if (p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED) {
    174     return (true);
    175   }
    176   return (false);
    177 }
    178 
    179 /*******************************************************************************
    180  *
    181  * Function         btm_dev_16_digit_authenticated
    182  *
    183  * Description      check device is authenticated by using 16 digit pin or MITM
    184  *
    185  * Returns          bool    true or false
    186  *
    187  ******************************************************************************/
    188 static bool btm_dev_16_digit_authenticated(tBTM_SEC_DEV_REC* p_dev_rec) {
    189   // BTM_SEC_16_DIGIT_PIN_AUTHED is set if MITM or 16 digit pin is used
    190   if (p_dev_rec->sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED) {
    191     return (true);
    192   }
    193   return (false);
    194 }
    195 
    196 /*******************************************************************************
    197  *
    198  * Function         btm_serv_trusted
    199  *
    200  * Description      check service is trusted
    201  *
    202  * Returns          bool    true or false
    203  *
    204  ******************************************************************************/
    205 static bool btm_serv_trusted(tBTM_SEC_DEV_REC* p_dev_rec,
    206                              tBTM_SEC_SERV_REC* p_serv_rec) {
    207   if (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
    208                                  p_serv_rec->service_id)) {
    209     return (true);
    210   }
    211   return (false);
    212 }
    213 
    214 /*******************************************************************************
    215  *
    216  * Function         BTM_SecRegister
    217  *
    218  * Description      Application manager calls this function to register for
    219  *                  security services.  There can be one and only one
    220  *                  application saving link keys.  BTM allows only first
    221  *                  registration.
    222  *
    223  * Returns          true if registered OK, else false
    224  *
    225  ******************************************************************************/
    226 bool BTM_SecRegister(tBTM_APPL_INFO* p_cb_info) {
    227   BT_OCTET16 temp_value = {0};
    228 
    229   BTM_TRACE_EVENT("%s application registered", __func__);
    230 
    231   LOG_INFO(LOG_TAG, "%s p_cb_info->p_le_callback == 0x%p", __func__,
    232            p_cb_info->p_le_callback);
    233   if (p_cb_info->p_le_callback) {
    234     BTM_TRACE_EVENT("%s SMP_Register( btm_proc_smp_cback )", __func__);
    235     SMP_Register(btm_proc_smp_cback);
    236     /* if no IR is loaded, need to regenerate all the keys */
    237     if (memcmp(btm_cb.devcb.id_keys.ir, &temp_value, sizeof(BT_OCTET16)) == 0) {
    238       btm_ble_reset_id();
    239     }
    240   } else {
    241     LOG_WARN(LOG_TAG, "%s p_cb_info->p_le_callback == NULL", __func__);
    242   }
    243 
    244   btm_cb.api = *p_cb_info;
    245   LOG_INFO(LOG_TAG, "%s btm_cb.api.p_le_callback = 0x%p ", __func__,
    246            btm_cb.api.p_le_callback);
    247   BTM_TRACE_EVENT("%s application registered", __func__);
    248   return (true);
    249 }
    250 
    251 /*******************************************************************************
    252  *
    253  * Function         BTM_SecRegisterLinkKeyNotificationCallback
    254  *
    255  * Description      Application manager calls this function to register for
    256  *                  link key notification.  When there is nobody registered
    257  *                  we should avoid changing link key
    258  *
    259  * Returns          true if registered OK, else false
    260  *
    261  ******************************************************************************/
    262 bool BTM_SecRegisterLinkKeyNotificationCallback(
    263     tBTM_LINK_KEY_CALLBACK* p_callback) {
    264   btm_cb.api.p_link_key_callback = p_callback;
    265   return true;
    266 }
    267 
    268 /*******************************************************************************
    269  *
    270  * Function         BTM_SecAddRmtNameNotifyCallback
    271  *
    272  * Description      Any profile can register to be notified when name of the
    273  *                  remote device is resolved.
    274  *
    275  * Returns          true if registered OK, else false
    276  *
    277  ******************************************************************************/
    278 bool BTM_SecAddRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK* p_callback) {
    279   int i;
    280 
    281   for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) {
    282     if (btm_cb.p_rmt_name_callback[i] == NULL) {
    283       btm_cb.p_rmt_name_callback[i] = p_callback;
    284       return (true);
    285     }
    286   }
    287 
    288   return (false);
    289 }
    290 
    291 /*******************************************************************************
    292  *
    293  * Function         BTM_SecDeleteRmtNameNotifyCallback
    294  *
    295  * Description      Any profile can deregister notification when a new Link Key
    296  *                  is generated per connection.
    297  *
    298  * Returns          true if OK, else false
    299  *
    300  ******************************************************************************/
    301 bool BTM_SecDeleteRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK* p_callback) {
    302   int i;
    303 
    304   for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) {
    305     if (btm_cb.p_rmt_name_callback[i] == p_callback) {
    306       btm_cb.p_rmt_name_callback[i] = NULL;
    307       return (true);
    308     }
    309   }
    310 
    311   return (false);
    312 }
    313 
    314 /*******************************************************************************
    315  *
    316  * Function         BTM_GetSecurityFlags
    317  *
    318  * Description      Get security flags for the device
    319  *
    320  * Returns          bool    true or false is device found
    321  *
    322  ******************************************************************************/
    323 bool BTM_GetSecurityFlags(const RawAddress& bd_addr, uint8_t* p_sec_flags) {
    324   tBTM_SEC_DEV_REC* p_dev_rec;
    325 
    326   p_dev_rec = btm_find_dev(bd_addr);
    327   if (p_dev_rec != NULL) {
    328     *p_sec_flags = (uint8_t)p_dev_rec->sec_flags;
    329     return (true);
    330   }
    331   BTM_TRACE_ERROR("BTM_GetSecurityFlags false");
    332   return (false);
    333 }
    334 
    335 /*******************************************************************************
    336  *
    337  * Function         BTM_GetSecurityFlagsByTransport
    338  *
    339  * Description      Get security flags for the device on a particular transport
    340  *
    341  * Returns          bool    true or false is device found
    342  *
    343  ******************************************************************************/
    344 bool BTM_GetSecurityFlagsByTransport(const RawAddress& bd_addr,
    345                                      uint8_t* p_sec_flags,
    346                                      tBT_TRANSPORT transport) {
    347   tBTM_SEC_DEV_REC* p_dev_rec;
    348 
    349   p_dev_rec = btm_find_dev(bd_addr);
    350   if (p_dev_rec != NULL) {
    351     if (transport == BT_TRANSPORT_BR_EDR)
    352       *p_sec_flags = (uint8_t)p_dev_rec->sec_flags;
    353     else
    354       *p_sec_flags = (uint8_t)(p_dev_rec->sec_flags >> 8);
    355 
    356     return (true);
    357   }
    358   BTM_TRACE_ERROR("BTM_GetSecurityFlags false");
    359   return (false);
    360 }
    361 
    362 /*******************************************************************************
    363  *
    364  * Function         BTM_SetPinType
    365  *
    366  * Description      Set PIN type for the device.
    367  *
    368  * Returns          void
    369  *
    370  ******************************************************************************/
    371 void BTM_SetPinType(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len) {
    372   BTM_TRACE_API(
    373       "BTM_SetPinType: pin type %d [variable-0, fixed-1], code %s, length %d",
    374       pin_type, (char*)pin_code, pin_code_len);
    375 
    376   /* If device is not up security mode will be set as a part of startup */
    377   if ((btm_cb.cfg.pin_type != pin_type) &&
    378       controller_get_interface()->get_is_ready()) {
    379     btsnd_hcic_write_pin_type(pin_type);
    380   }
    381 
    382   btm_cb.cfg.pin_type = pin_type;
    383   btm_cb.cfg.pin_code_len = pin_code_len;
    384   memcpy(btm_cb.cfg.pin_code, pin_code, pin_code_len);
    385 }
    386 
    387 /*******************************************************************************
    388  *
    389  * Function         BTM_SetPairableMode
    390  *
    391  * Description      Enable or disable pairing
    392  *
    393  * Parameters       allow_pairing - (true or false) whether or not the device
    394  *                      allows pairing.
    395  *                  connect_only_paired - (true or false) whether or not to
    396  *                      only allow paired devices to connect.
    397  *
    398  * Returns          void
    399  *
    400  ******************************************************************************/
    401 void BTM_SetPairableMode(bool allow_pairing, bool connect_only_paired) {
    402   BTM_TRACE_API(
    403       "BTM_SetPairableMode()  allow_pairing: %u   connect_only_paired: %u",
    404       allow_pairing, connect_only_paired);
    405 
    406   btm_cb.pairing_disabled = !allow_pairing;
    407   btm_cb.connect_only_paired = connect_only_paired;
    408 }
    409 
    410 /*******************************************************************************
    411  *
    412  * Function         BTM_SetSecureConnectionsOnly
    413  *
    414  * Description      Enable or disable default treatment for Mode 4 Level 0
    415  *                  services
    416  *
    417  * Parameter        secure_connections_only_mode -
    418  *                  true means that the device should treat Mode 4 Level 0
    419  *                       services as services of other levels.
    420  *                  false means that the device should provide default
    421  *                        treatment for Mode 4 Level 0 services.
    422  *
    423  * Returns          void
    424  *
    425  ******************************************************************************/
    426 void BTM_SetSecureConnectionsOnly(bool secure_connections_only_mode) {
    427   BTM_TRACE_API("%s: Mode : %u", __func__, secure_connections_only_mode);
    428 
    429   btm_cb.devcb.secure_connections_only = secure_connections_only_mode;
    430   btm_cb.security_mode = BTM_SEC_MODE_SC;
    431 }
    432 #define BTM_NO_AVAIL_SEC_SERVICES ((uint16_t)0xffff)
    433 
    434 /*******************************************************************************
    435  *
    436  * Function         BTM_SetSecurityLevel
    437  *
    438  * Description      Register service security level with Security Manager
    439  *
    440  * Parameters:      is_originator - true if originating the connection
    441  *                  p_name      - Name of the service relevant only if
    442  *                                authorization will show this name to user.
    443  *                                Ignored if BTM_SEC_SERVICE_NAME_LEN is 0.
    444  *                  service_id  - service ID for the service passed to
    445  *                                authorization callback
    446  *                  sec_level   - bit mask of the security features
    447  *                  psm         - L2CAP PSM
    448  *                  mx_proto_id - protocol ID of multiplexing proto below
    449  *                  mx_chan_id  - channel ID of multiplexing proto below
    450  *
    451  * Returns          true if registered OK, else false
    452  *
    453  ******************************************************************************/
    454 bool BTM_SetSecurityLevel(bool is_originator, const char* p_name,
    455                           uint8_t service_id, uint16_t sec_level, uint16_t psm,
    456                           uint32_t mx_proto_id, uint32_t mx_chan_id) {
    457 #if (L2CAP_UCD_INCLUDED == TRUE)
    458   CONNECTION_TYPE conn_type;
    459 
    460   if (is_originator)
    461     conn_type = CONN_ORIENT_ORIG;
    462   else
    463     conn_type = CONN_ORIENT_TERM;
    464 
    465   return (btm_sec_set_security_level(conn_type, p_name, service_id, sec_level,
    466                                      psm, mx_proto_id, mx_chan_id));
    467 #else
    468   return (btm_sec_set_security_level(is_originator, p_name, service_id,
    469                                      sec_level, psm, mx_proto_id, mx_chan_id));
    470 #endif
    471 }
    472 
    473 /*******************************************************************************
    474  *
    475  * Function         btm_sec_set_security_level
    476  *
    477  * Description      Register service security level with Security Manager
    478  *
    479  * Parameters:      conn_type   - true if originating the connection
    480  *                  p_name      - Name of the service relevant only if
    481  *                                authorization will show this name to user.
    482  *                                Ignored if BTM_SEC_SERVICE_NAME_LEN is 0.
    483  *                  service_id  - service ID for the service passed to
    484  *                                authorization callback
    485  *                  sec_level   - bit mask of the security features
    486  *                  psm         - L2CAP PSM
    487  *                  mx_proto_id - protocol ID of multiplexing proto below
    488  *                  mx_chan_id  - channel ID of multiplexing proto below
    489  *
    490  * Returns          true if registered OK, else false
    491  *
    492  ******************************************************************************/
    493 static bool btm_sec_set_security_level(CONNECTION_TYPE conn_type,
    494                                        const char* p_name, uint8_t service_id,
    495                                        uint16_t sec_level, uint16_t psm,
    496                                        uint32_t mx_proto_id,
    497                                        uint32_t mx_chan_id) {
    498   tBTM_SEC_SERV_REC* p_srec;
    499   uint16_t index;
    500   uint16_t first_unused_record = BTM_NO_AVAIL_SEC_SERVICES;
    501   bool record_allocated = false;
    502   bool is_originator;
    503 #if (L2CAP_UCD_INCLUDED == TRUE)
    504   bool is_ucd;
    505 
    506   if (conn_type & CONNECTION_TYPE_ORIG_MASK)
    507     is_originator = true;
    508   else
    509     is_originator = false;
    510 
    511   if (conn_type & CONNECTION_TYPE_CONNLESS_MASK) {
    512     is_ucd = true;
    513   } else {
    514     is_ucd = false;
    515   }
    516 #else
    517   is_originator = conn_type;
    518 #endif
    519 
    520   BTM_TRACE_API("%s : sec: 0x%x", __func__, sec_level);
    521 
    522   /* See if the record can be reused (same service name, psm, mx_proto_id,
    523      service_id, and mx_chan_id), or obtain the next unused record */
    524 
    525   p_srec = &btm_cb.sec_serv_rec[0];
    526 
    527   for (index = 0; index < BTM_SEC_MAX_SERVICE_RECORDS; index++, p_srec++) {
    528     /* Check if there is already a record for this service */
    529     if (p_srec->security_flags & BTM_SEC_IN_USE) {
    530 #if BTM_SEC_SERVICE_NAME_LEN > 0
    531       if (p_srec->psm == psm && p_srec->mx_proto_id == mx_proto_id &&
    532           service_id == p_srec->service_id && p_name &&
    533           (!strncmp(p_name, (char*)p_srec->orig_service_name,
    534                     /* strlcpy replaces end char with termination char*/
    535                     BTM_SEC_SERVICE_NAME_LEN - 1) ||
    536            !strncmp(p_name, (char*)p_srec->term_service_name,
    537                     /* strlcpy replaces end char with termination char*/
    538                     BTM_SEC_SERVICE_NAME_LEN - 1)))
    539 #else
    540       if (p_srec->psm == psm && p_srec->mx_proto_id == mx_proto_id &&
    541           service_id == p_srec->service_id)
    542 #endif
    543       {
    544         record_allocated = true;
    545         break;
    546       }
    547     }
    548     /* Mark the first available service record */
    549     else if (!record_allocated) {
    550       memset(p_srec, 0, sizeof(tBTM_SEC_SERV_REC));
    551       record_allocated = true;
    552       first_unused_record = index;
    553     }
    554   }
    555 
    556   if (!record_allocated) {
    557     BTM_TRACE_WARNING("BTM_SEC_REG: Out of Service Records (%d)",
    558                       BTM_SEC_MAX_SERVICE_RECORDS);
    559     return (record_allocated);
    560   }
    561 
    562   /* Process the request if service record is valid */
    563   /* If a duplicate service wasn't found, use the first available */
    564   if (index >= BTM_SEC_MAX_SERVICE_RECORDS) {
    565     index = first_unused_record;
    566     p_srec = &btm_cb.sec_serv_rec[index];
    567   }
    568 
    569   p_srec->psm = psm;
    570   p_srec->service_id = service_id;
    571   p_srec->mx_proto_id = mx_proto_id;
    572 
    573   if (is_originator) {
    574     p_srec->orig_mx_chan_id = mx_chan_id;
    575 #if BTM_SEC_SERVICE_NAME_LEN > 0
    576     strlcpy((char*)p_srec->orig_service_name, p_name,
    577             BTM_SEC_SERVICE_NAME_LEN + 1);
    578 #endif
    579 /* clear out the old setting, just in case it exists */
    580 #if (L2CAP_UCD_INCLUDED == TRUE)
    581     if (is_ucd) {
    582       p_srec->ucd_security_flags &= ~(
    583           BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT |
    584           BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM | BTM_SEC_FORCE_MASTER |
    585           BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE);
    586     } else
    587 #endif
    588     {
    589       p_srec->security_flags &= ~(
    590           BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT |
    591           BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM | BTM_SEC_FORCE_MASTER |
    592           BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE);
    593     }
    594 
    595     /* Parameter validation.  Originator should not set requirements for
    596      * incoming connections */
    597     sec_level &=
    598         ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE |
    599           BTM_SEC_IN_MITM | BTM_SEC_IN_MIN_16_DIGIT_PIN);
    600 
    601     if (btm_cb.security_mode == BTM_SEC_MODE_SP ||
    602         btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
    603         btm_cb.security_mode == BTM_SEC_MODE_SC) {
    604       if (sec_level & BTM_SEC_OUT_AUTHENTICATE) sec_level |= BTM_SEC_OUT_MITM;
    605     }
    606 
    607     /* Make sure the authenticate bit is set, when encrypt bit is set */
    608     if (sec_level & BTM_SEC_OUT_ENCRYPT) sec_level |= BTM_SEC_OUT_AUTHENTICATE;
    609 
    610 /* outgoing connections usually set the security level right before
    611  * the connection is initiated.
    612  * set it to be the outgoing service */
    613 #if (L2CAP_UCD_INCLUDED == TRUE)
    614     if (is_ucd == false)
    615 #endif
    616     {
    617       btm_cb.p_out_serv = p_srec;
    618     }
    619   } else {
    620     p_srec->term_mx_chan_id = mx_chan_id;
    621 #if BTM_SEC_SERVICE_NAME_LEN > 0
    622     strlcpy((char*)p_srec->term_service_name, p_name,
    623             BTM_SEC_SERVICE_NAME_LEN + 1);
    624 #endif
    625 /* clear out the old setting, just in case it exists */
    626 #if (L2CAP_UCD_INCLUDED == TRUE)
    627     if (is_ucd) {
    628       p_srec->ucd_security_flags &=
    629           ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT |
    630             BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM | BTM_SEC_FORCE_MASTER |
    631             BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE |
    632             BTM_SEC_ATTEMPT_SLAVE | BTM_SEC_IN_MIN_16_DIGIT_PIN);
    633     } else
    634 #endif
    635     {
    636       p_srec->security_flags &=
    637           ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT |
    638             BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM | BTM_SEC_FORCE_MASTER |
    639             BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE |
    640             BTM_SEC_ATTEMPT_SLAVE | BTM_SEC_IN_MIN_16_DIGIT_PIN);
    641     }
    642 
    643     /* Parameter validation.  Acceptor should not set requirements for outgoing
    644      * connections */
    645     sec_level &= ~(BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT |
    646                    BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM);
    647 
    648     if (btm_cb.security_mode == BTM_SEC_MODE_SP ||
    649         btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
    650         btm_cb.security_mode == BTM_SEC_MODE_SC) {
    651       if (sec_level & BTM_SEC_IN_AUTHENTICATE) sec_level |= BTM_SEC_IN_MITM;
    652     }
    653 
    654     /* Make sure the authenticate bit is set, when encrypt bit is set */
    655     if (sec_level & BTM_SEC_IN_ENCRYPT) sec_level |= BTM_SEC_IN_AUTHENTICATE;
    656   }
    657 
    658 #if (L2CAP_UCD_INCLUDED == TRUE)
    659   if (is_ucd) {
    660     p_srec->security_flags |= (uint16_t)(BTM_SEC_IN_USE);
    661     p_srec->ucd_security_flags |= (uint16_t)(sec_level | BTM_SEC_IN_USE);
    662   } else {
    663     p_srec->security_flags |= (uint16_t)(sec_level | BTM_SEC_IN_USE);
    664   }
    665 
    666   BTM_TRACE_API(
    667       "BTM_SEC_REG[%d]: id %d, conn_type 0x%x, psm 0x%04x, proto_id %d, "
    668       "chan_id %d",
    669       index, service_id, conn_type, psm, mx_proto_id, mx_chan_id);
    670 
    671   BTM_TRACE_API(
    672       "               : security_flags: 0x%04x, ucd_security_flags: 0x%04x",
    673       p_srec->security_flags, p_srec->ucd_security_flags);
    674 
    675 #if BTM_SEC_SERVICE_NAME_LEN > 0
    676   BTM_TRACE_API("               : service name [%s] (up to %d chars saved)",
    677                 p_name, BTM_SEC_SERVICE_NAME_LEN);
    678 #endif
    679 #else
    680   p_srec->security_flags |= (uint16_t)(sec_level | BTM_SEC_IN_USE);
    681 
    682   BTM_TRACE_API(
    683       "BTM_SEC_REG[%d]: id %d, is_orig %d, psm 0x%04x, proto_id %d, chan_id %d",
    684       index, service_id, is_originator, psm, mx_proto_id, mx_chan_id);
    685 
    686 #if BTM_SEC_SERVICE_NAME_LEN > 0
    687   BTM_TRACE_API(
    688       "               : sec: 0x%x, service name [%s] (up to %d chars saved)",
    689       p_srec->security_flags, p_name, BTM_SEC_SERVICE_NAME_LEN);
    690 #endif
    691 #endif
    692 
    693   return (record_allocated);
    694 }
    695 
    696 /*******************************************************************************
    697  *
    698  * Function         BTM_SecClrService
    699  *
    700  * Description      Removes specified service record(s) from the security
    701  *                  database. All service records with the specified name are
    702  *                  removed. Typically used only by devices with limited RAM so
    703  *                  that it can reuse an old security service record.
    704  *
    705  *                  Note: Unpredictable results may occur if a service is
    706  *                      cleared that is still in use by an application/profile.
    707  *
    708  * Parameters       Service ID - Id of the service to remove. '0' removes all
    709  *                          service records (except SDP).
    710  *
    711  * Returns          Number of records that were freed.
    712  *
    713  ******************************************************************************/
    714 uint8_t BTM_SecClrService(uint8_t service_id) {
    715   tBTM_SEC_SERV_REC* p_srec = &btm_cb.sec_serv_rec[0];
    716   uint8_t num_freed = 0;
    717   int i;
    718 
    719   for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++) {
    720     /* Delete services with specified name (if in use and not SDP) */
    721     if ((p_srec->security_flags & BTM_SEC_IN_USE) &&
    722         (p_srec->psm != BT_PSM_SDP) &&
    723         (!service_id || (service_id == p_srec->service_id))) {
    724       BTM_TRACE_API("BTM_SEC_CLR[%d]: id %d", i, service_id);
    725       p_srec->security_flags = 0;
    726 #if (L2CAP_UCD_INCLUDED == TRUE)
    727       p_srec->ucd_security_flags = 0;
    728 #endif
    729       num_freed++;
    730     }
    731   }
    732 
    733   return (num_freed);
    734 }
    735 
    736 /*******************************************************************************
    737  *
    738  * Function         btm_sec_clr_service_by_psm
    739  *
    740  * Description      Removes specified service record from the security database.
    741  *                  All service records with the specified psm are removed.
    742  *                  Typically used by L2CAP to free up the service record used
    743  *                  by dynamic PSM clients when the channel is closed.
    744  *                  The given psm must be a virtual psm.
    745  *
    746  * Parameters       Service ID - Id of the service to remove. '0' removes all
    747  *                          service records (except SDP).
    748  *
    749  * Returns          Number of records that were freed.
    750  *
    751  ******************************************************************************/
    752 uint8_t btm_sec_clr_service_by_psm(uint16_t psm) {
    753   tBTM_SEC_SERV_REC* p_srec = &btm_cb.sec_serv_rec[0];
    754   uint8_t num_freed = 0;
    755   int i;
    756 
    757   for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++) {
    758     /* Delete services with specified name (if in use and not SDP) */
    759     if ((p_srec->security_flags & BTM_SEC_IN_USE) && (p_srec->psm == psm)) {
    760       BTM_TRACE_API("BTM_SEC_CLR[%d]: id %d ", i, p_srec->service_id);
    761       p_srec->security_flags = 0;
    762       num_freed++;
    763     }
    764   }
    765   BTM_TRACE_API("btm_sec_clr_service_by_psm psm:0x%x num_freed:%d", psm,
    766                 num_freed);
    767 
    768   return (num_freed);
    769 }
    770 
    771 /*******************************************************************************
    772  *
    773  * Function         btm_sec_clr_temp_auth_service
    774  *
    775  * Description      Removes specified device record's temporary authorization
    776  *                  flag from the security database.
    777  *
    778  * Parameters       Device address to be cleared
    779  *
    780  * Returns          void.
    781  *
    782  ******************************************************************************/
    783 void btm_sec_clr_temp_auth_service(const RawAddress& bda) {
    784   tBTM_SEC_DEV_REC* p_dev_rec;
    785 
    786   p_dev_rec = btm_find_dev(bda);
    787   if (p_dev_rec == NULL) {
    788     BTM_TRACE_WARNING("btm_sec_clr_temp_auth_service() - no dev CB");
    789     return;
    790   }
    791 
    792   /* Reset the temporary authorized flag so that next time (untrusted) service
    793    * is accessed autorization will take place */
    794   if (p_dev_rec->last_author_service_id != BTM_SEC_NO_LAST_SERVICE_ID &&
    795       p_dev_rec->p_cur_service) {
    796     VLOG(1) << __func__ << " clearing device: " << bda;
    797 
    798     p_dev_rec->last_author_service_id = BTM_SEC_NO_LAST_SERVICE_ID;
    799   }
    800 }
    801 
    802 /*******************************************************************************
    803  *
    804  * Function         BTM_PINCodeReply
    805  *
    806  * Description      This function is called after Security Manager submitted
    807  *                  PIN code request to the UI.
    808  *
    809  * Parameters:      bd_addr      - Address of the device for which PIN was
    810  *                                 requested
    811  *                  res          - result of the operation BTM_SUCCESS
    812  *                                 if success
    813  *                  pin_len      - length in bytes of the PIN Code
    814  *                  p_pin        - pointer to array with the PIN Code
    815  *                  trusted_mask - bitwise OR of trusted services
    816  *                                 (array of uint32_t)
    817  *
    818  ******************************************************************************/
    819 void BTM_PINCodeReply(const RawAddress& bd_addr, uint8_t res, uint8_t pin_len,
    820                       uint8_t* p_pin, uint32_t trusted_mask[]) {
    821   tBTM_SEC_DEV_REC* p_dev_rec;
    822 
    823   BTM_TRACE_API(
    824       "BTM_PINCodeReply(): PairState: %s   PairFlags: 0x%02x  PinLen:%d  "
    825       "Result:%d",
    826       btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, pin_len,
    827       res);
    828 
    829   /* If timeout already expired or has been canceled, ignore the reply */
    830   if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) {
    831     BTM_TRACE_WARNING("BTM_PINCodeReply() - Wrong State: %d",
    832                       btm_cb.pairing_state);
    833     return;
    834   }
    835 
    836   if (bd_addr != btm_cb.pairing_bda) {
    837     BTM_TRACE_ERROR("BTM_PINCodeReply() - Wrong BD Addr");
    838     return;
    839   }
    840 
    841   p_dev_rec = btm_find_dev(bd_addr);
    842   if (p_dev_rec == NULL) {
    843     BTM_TRACE_ERROR("BTM_PINCodeReply() - no dev CB");
    844     return;
    845   }
    846 
    847   if ((pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL))
    848     res = BTM_ILLEGAL_VALUE;
    849 
    850   if (res != BTM_SUCCESS) {
    851     /* if peer started dd OR we started dd and pre-fetch pin was not used send
    852      * negative reply */
    853     if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) ||
    854         ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
    855          (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE))) {
    856       /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed
    857        * event */
    858       btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
    859       btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
    860 
    861       btsnd_hcic_pin_code_neg_reply(bd_addr);
    862     } else {
    863       p_dev_rec->security_required = BTM_SEC_NONE;
    864       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
    865     }
    866     return;
    867   }
    868   if (trusted_mask)
    869     BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask);
    870   p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED;
    871   p_dev_rec->pin_code_length = pin_len;
    872   if (pin_len >= 16) {
    873     p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
    874   }
    875 
    876   if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
    877       (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) &&
    878       (btm_cb.security_mode_changed == false)) {
    879     /* This is start of the dedicated bonding if local device is 2.0 */
    880     btm_cb.pin_code_len = pin_len;
    881     memcpy(btm_cb.pin_code, p_pin, pin_len);
    882 
    883     btm_cb.security_mode_changed = true;
    884 #ifdef APPL_AUTH_WRITE_EXCEPTION
    885     if (!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr))
    886 #endif
    887       btsnd_hcic_write_auth_enable(true);
    888 
    889     btm_cb.acl_disc_reason = 0xff;
    890 
    891     /* if we rejected incoming connection request, we have to wait
    892      * HCI_Connection_Complete event */
    893     /*  before originating  */
    894     if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) {
    895       BTM_TRACE_WARNING(
    896           "BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected "
    897           "incoming connection");
    898       /* we change state little bit early so btm_sec_connected() will originate
    899        * connection */
    900       /*   when existing ACL link is down completely */
    901       btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
    902     }
    903     /* if we already accepted incoming connection from pairing device */
    904     else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) {
    905       BTM_TRACE_WARNING(
    906           "BTM_PINCodeReply(): link is connecting so wait pin code request "
    907           "from peer");
    908       btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
    909     } else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) {
    910       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
    911       p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED;
    912 
    913       if (btm_cb.api.p_auth_complete_callback)
    914         (*btm_cb.api.p_auth_complete_callback)(
    915             p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
    916             HCI_ERR_AUTH_FAILURE);
    917     }
    918     return;
    919   }
    920 
    921   btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
    922   btm_cb.acl_disc_reason = HCI_SUCCESS;
    923 
    924   btsnd_hcic_pin_code_req_reply(bd_addr, pin_len, p_pin);
    925 }
    926 
    927 /*******************************************************************************
    928  *
    929  * Function         btm_sec_bond_by_transport
    930  *
    931  * Description      this is the bond function that will start either SSP or SMP.
    932  *
    933  * Parameters:      bd_addr      - Address of the device to bond
    934  *                  pin_len      - length in bytes of the PIN Code
    935  *                  p_pin        - pointer to array with the PIN Code
    936  *                  trusted_mask - bitwise OR of trusted services
    937  *                                 (array of uint32_t)
    938  *
    939  *  Note: After 2.1 parameters are not used and preserved here not to change API
    940  ******************************************************************************/
    941 tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr,
    942                                       tBT_TRANSPORT transport, uint8_t pin_len,
    943                                       uint8_t* p_pin, uint32_t trusted_mask[]) {
    944   tBTM_SEC_DEV_REC* p_dev_rec;
    945   tBTM_STATUS status;
    946   uint8_t* p_features;
    947   uint8_t ii;
    948   tACL_CONN* p = btm_bda_to_acl(bd_addr, transport);
    949   VLOG(1) << __func__ << " BDA: " << bd_addr;
    950 
    951   BTM_TRACE_DEBUG("btm_sec_bond_by_transport: Transport used %d", transport);
    952 
    953   /* Other security process is in progress */
    954   if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) {
    955     BTM_TRACE_ERROR("BTM_SecBond: already busy in state: %s",
    956                     btm_pair_state_descr(btm_cb.pairing_state));
    957     return (BTM_WRONG_MODE);
    958   }
    959 
    960   p_dev_rec = btm_find_or_alloc_dev(bd_addr);
    961   if (p_dev_rec == NULL) {
    962     return (BTM_NO_RESOURCES);
    963   }
    964 
    965   if (!controller_get_interface()->get_is_ready()) {
    966     BTM_TRACE_ERROR("%s controller module is not ready", __func__);
    967     return (BTM_NO_RESOURCES);
    968   }
    969 
    970   BTM_TRACE_DEBUG("before update sec_flags=0x%x", p_dev_rec->sec_flags);
    971 
    972   /* Finished if connection is active and already paired */
    973   if (((p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE) &&
    974        transport == BT_TRANSPORT_BR_EDR &&
    975        (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) ||
    976       ((p_dev_rec->ble_hci_handle != BTM_SEC_INVALID_HANDLE) &&
    977        transport == BT_TRANSPORT_LE &&
    978        (p_dev_rec->sec_flags & BTM_SEC_LE_AUTHENTICATED))) {
    979     BTM_TRACE_WARNING("BTM_SecBond -> Already Paired");
    980     return (BTM_SUCCESS);
    981   }
    982 
    983   /* Tell controller to get rid of the link key if it has one stored */
    984   if ((BTM_DeleteStoredLinkKey(&bd_addr, NULL)) != BTM_SUCCESS)
    985     return (BTM_NO_RESOURCES);
    986 
    987   /* Save the PIN code if we got a valid one */
    988   if (p_pin && (pin_len <= PIN_CODE_LEN) && (pin_len != 0)) {
    989     btm_cb.pin_code_len = pin_len;
    990     p_dev_rec->pin_code_length = pin_len;
    991     memcpy(btm_cb.pin_code, p_pin, PIN_CODE_LEN);
    992   }
    993 
    994   btm_cb.pairing_bda = bd_addr;
    995 
    996   btm_cb.pairing_flags = BTM_PAIR_FLAGS_WE_STARTED_DD;
    997 
    998   p_dev_rec->security_required = BTM_SEC_OUT_AUTHENTICATE;
    999   p_dev_rec->is_originator = true;
   1000   if (trusted_mask)
   1001     BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask);
   1002 
   1003   if (transport == BT_TRANSPORT_LE) {
   1004     btm_ble_init_pseudo_addr(p_dev_rec, bd_addr);
   1005     p_dev_rec->sec_flags &= ~BTM_SEC_LE_MASK;
   1006 
   1007     if (SMP_Pair(bd_addr) == SMP_STARTED) {
   1008       btm_cb.pairing_flags |= BTM_PAIR_FLAGS_LE_ACTIVE;
   1009       p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
   1010       btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
   1011       return BTM_CMD_STARTED;
   1012     }
   1013 
   1014     btm_cb.pairing_flags = 0;
   1015     return (BTM_NO_RESOURCES);
   1016   }
   1017 
   1018   p_dev_rec->sec_flags &=
   1019       ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED |
   1020         BTM_SEC_ROLE_SWITCHED | BTM_SEC_LINK_KEY_AUTHED);
   1021 
   1022   BTM_TRACE_DEBUG("after update sec_flags=0x%x", p_dev_rec->sec_flags);
   1023   if (!controller_get_interface()->supports_simple_pairing()) {
   1024     /* The special case when we authenticate keyboard.  Set pin type to fixed */
   1025     /* It would be probably better to do it from the application, but it is */
   1026     /* complicated */
   1027     if (((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) ==
   1028          BTM_COD_MAJOR_PERIPHERAL) &&
   1029         (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD) &&
   1030         (btm_cb.cfg.pin_type != HCI_PIN_TYPE_FIXED)) {
   1031       btm_cb.pin_type_changed = true;
   1032       btsnd_hcic_write_pin_type(HCI_PIN_TYPE_FIXED);
   1033     }
   1034   }
   1035 
   1036   for (ii = 0; ii <= HCI_EXT_FEATURES_PAGE_MAX; ii++) {
   1037     p_features = p_dev_rec->feature_pages[ii];
   1038     BTM_TRACE_EVENT("  remote_features page[%1d] = %02x-%02x-%02x-%02x", ii,
   1039                     p_features[0], p_features[1], p_features[2], p_features[3]);
   1040     BTM_TRACE_EVENT("                              %02x-%02x-%02x-%02x",
   1041                     p_features[4], p_features[5], p_features[6], p_features[7]);
   1042   }
   1043 
   1044   BTM_TRACE_EVENT("BTM_SecBond: Remote sm4: 0x%x  HCI Handle: 0x%04x",
   1045                   p_dev_rec->sm4, p_dev_rec->hci_handle);
   1046 
   1047 #if (BTM_SEC_FORCE_RNR_FOR_DBOND == TRUE)
   1048   p_dev_rec->sec_flags &= ~BTM_SEC_NAME_KNOWN;
   1049 #endif
   1050 
   1051   /* If connection already exists... */
   1052   if (p && p->hci_handle != BTM_SEC_INVALID_HANDLE) {
   1053     btm_sec_start_authentication(p_dev_rec);
   1054 
   1055     btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
   1056 
   1057     /* Mark lcb as bonding */
   1058     l2cu_update_lcb_4_bonding(bd_addr, true);
   1059     return (BTM_CMD_STARTED);
   1060   }
   1061 
   1062   BTM_TRACE_DEBUG("sec mode: %d sm4:x%x", btm_cb.security_mode, p_dev_rec->sm4);
   1063   if (!controller_get_interface()->supports_simple_pairing() ||
   1064       (p_dev_rec->sm4 == BTM_SM4_KNOWN)) {
   1065     if (btm_sec_check_prefetch_pin(p_dev_rec)) return (BTM_CMD_STARTED);
   1066   }
   1067   if ((btm_cb.security_mode == BTM_SEC_MODE_SP ||
   1068        btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
   1069        btm_cb.security_mode == BTM_SEC_MODE_SC) &&
   1070       BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
   1071     /* local is 2.1 and peer is unknown */
   1072     if ((p_dev_rec->sm4 & BTM_SM4_CONN_PEND) == 0) {
   1073       /* we are not accepting connection request from peer
   1074        * -> RNR (to learn if peer is 2.1)
   1075        * RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */
   1076       btm_sec_change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME);
   1077       status = BTM_ReadRemoteDeviceName(bd_addr, NULL, BT_TRANSPORT_BR_EDR);
   1078     } else {
   1079       /* We are accepting connection request from peer */
   1080       btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
   1081       status = BTM_CMD_STARTED;
   1082     }
   1083     BTM_TRACE_DEBUG("State:%s sm4: 0x%x sec_state:%d",
   1084                     btm_pair_state_descr(btm_cb.pairing_state), p_dev_rec->sm4,
   1085                     p_dev_rec->sec_state);
   1086   } else {
   1087     /* both local and peer are 2.1  */
   1088     status = btm_sec_dd_create_conn(p_dev_rec);
   1089   }
   1090 
   1091   if (status != BTM_CMD_STARTED) {
   1092     BTM_TRACE_ERROR(
   1093         "%s BTM_ReadRemoteDeviceName or btm_sec_dd_create_conn error: 0x%x",
   1094         __func__, (int)status);
   1095     btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   1096   }
   1097 
   1098   return status;
   1099 }
   1100 
   1101 /*******************************************************************************
   1102  *
   1103  * Function         BTM_SecBondByTransport
   1104  *
   1105  * Description      This function is called to perform bonding with peer device.
   1106  *                  If the connection is already up, but not secure, pairing
   1107  *                  is attempted.  If already paired BTM_SUCCESS is returned.
   1108  *
   1109  * Parameters:      bd_addr      - Address of the device to bond
   1110  *                  transport    - doing SSP over BR/EDR or SMP over LE
   1111  *                  pin_len      - length in bytes of the PIN Code
   1112  *                  p_pin        - pointer to array with the PIN Code
   1113  *                  trusted_mask - bitwise OR of trusted services
   1114  *                                 (array of uint32_t)
   1115  *
   1116  *  Note: After 2.1 parameters are not used and preserved here not to change API
   1117  ******************************************************************************/
   1118 tBTM_STATUS BTM_SecBondByTransport(const RawAddress& bd_addr,
   1119                                    tBT_TRANSPORT transport, uint8_t pin_len,
   1120                                    uint8_t* p_pin, uint32_t trusted_mask[]) {
   1121   tBT_DEVICE_TYPE dev_type;
   1122   tBLE_ADDR_TYPE addr_type;
   1123 
   1124   BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type);
   1125   /* LE device, do SMP pairing */
   1126   if ((transport == BT_TRANSPORT_LE && (dev_type & BT_DEVICE_TYPE_BLE) == 0) ||
   1127       (transport == BT_TRANSPORT_BR_EDR &&
   1128        (dev_type & BT_DEVICE_TYPE_BREDR) == 0)) {
   1129     return BTM_ILLEGAL_ACTION;
   1130   }
   1131   return btm_sec_bond_by_transport(bd_addr, transport, pin_len, p_pin,
   1132                                    trusted_mask);
   1133 }
   1134 
   1135 /*******************************************************************************
   1136  *
   1137  * Function         BTM_SecBond
   1138  *
   1139  * Description      This function is called to perform bonding with peer device.
   1140  *                  If the connection is already up, but not secure, pairing
   1141  *                  is attempted.  If already paired BTM_SUCCESS is returned.
   1142  *
   1143  * Parameters:      bd_addr      - Address of the device to bond
   1144  *                  pin_len      - length in bytes of the PIN Code
   1145  *                  p_pin        - pointer to array with the PIN Code
   1146  *                  trusted_mask - bitwise OR of trusted services
   1147  *                                 (array of uint32_t)
   1148  *
   1149  *  Note: After 2.1 parameters are not used and preserved here not to change API
   1150  ******************************************************************************/
   1151 tBTM_STATUS BTM_SecBond(const RawAddress& bd_addr, uint8_t pin_len,
   1152                         uint8_t* p_pin, uint32_t trusted_mask[]) {
   1153   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
   1154   if (BTM_UseLeLink(bd_addr)) transport = BT_TRANSPORT_LE;
   1155   return btm_sec_bond_by_transport(bd_addr, transport, pin_len, p_pin,
   1156                                    trusted_mask);
   1157 }
   1158 /*******************************************************************************
   1159  *
   1160  * Function         BTM_SecBondCancel
   1161  *
   1162  * Description      This function is called to cancel ongoing bonding process
   1163  *                  with peer device.
   1164  *
   1165  * Parameters:      bd_addr      - Address of the peer device
   1166  *                  transport    - false for BR/EDR link; true for LE link
   1167  *
   1168  ******************************************************************************/
   1169 tBTM_STATUS BTM_SecBondCancel(const RawAddress& bd_addr) {
   1170   tBTM_SEC_DEV_REC* p_dev_rec;
   1171 
   1172   BTM_TRACE_API("BTM_SecBondCancel()  State: %s flags:0x%x",
   1173                 btm_pair_state_descr(btm_cb.pairing_state),
   1174                 btm_cb.pairing_flags);
   1175   p_dev_rec = btm_find_dev(bd_addr);
   1176   if (!p_dev_rec || btm_cb.pairing_bda != bd_addr) {
   1177     return BTM_UNKNOWN_ADDR;
   1178   }
   1179 
   1180   if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) {
   1181     if (p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING) {
   1182       BTM_TRACE_DEBUG("Cancel LE pairing");
   1183       if (SMP_PairCancel(bd_addr)) {
   1184         return BTM_CMD_STARTED;
   1185       }
   1186     }
   1187     return BTM_WRONG_MODE;
   1188   }
   1189 
   1190   BTM_TRACE_DEBUG("hci_handle:0x%x sec_state:%d", p_dev_rec->hci_handle,
   1191                   p_dev_rec->sec_state);
   1192   if (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_cb.pairing_state &&
   1193       BTM_PAIR_FLAGS_WE_STARTED_DD & btm_cb.pairing_flags) {
   1194     /* pre-fetching pin for dedicated bonding */
   1195     btm_sec_bond_cancel_complete();
   1196     return BTM_SUCCESS;
   1197   }
   1198 
   1199   /* If this BDA is in a bonding procedure */
   1200   if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   1201       (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) {
   1202     /* If the HCI link is up */
   1203     if (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE) {
   1204       /* If some other thread disconnecting, we do not send second command */
   1205       if ((p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING) ||
   1206           (p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH))
   1207         return (BTM_CMD_STARTED);
   1208 
   1209       /* If the HCI link was set up by Bonding process */
   1210       if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)
   1211         return btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_PEER_USER,
   1212                                            p_dev_rec->hci_handle);
   1213       else
   1214         l2cu_update_lcb_4_bonding(bd_addr, false);
   1215 
   1216       return BTM_NOT_AUTHORIZED;
   1217     } else /*HCI link is not up */
   1218     {
   1219       /* If the HCI link creation was started by Bonding process */
   1220       if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) {
   1221         btsnd_hcic_create_conn_cancel(bd_addr);
   1222         return BTM_CMD_STARTED;
   1223       }
   1224       if (btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) {
   1225         BTM_CancelRemoteDeviceName();
   1226         btm_cb.pairing_flags |= BTM_PAIR_FLAGS_WE_CANCEL_DD;
   1227         return BTM_CMD_STARTED;
   1228       }
   1229       return BTM_NOT_AUTHORIZED;
   1230     }
   1231   }
   1232 
   1233   return BTM_WRONG_MODE;
   1234 }
   1235 
   1236 /*******************************************************************************
   1237  *
   1238  * Function         BTM_SecGetDeviceLinkKey
   1239  *
   1240  * Description      This function is called to obtain link key for the device
   1241  *                  it returns BTM_SUCCESS if link key is available, or
   1242  *                  BTM_UNKNOWN_ADDR if Security Manager does not know about
   1243  *                  the device or device record does not contain link key info
   1244  *
   1245  * Parameters:      bd_addr      - Address of the device
   1246  *                  link_key     - Link Key is copied into this array
   1247  *
   1248  ******************************************************************************/
   1249 tBTM_STATUS BTM_SecGetDeviceLinkKey(const RawAddress& bd_addr,
   1250                                     LINK_KEY link_key) {
   1251   tBTM_SEC_DEV_REC* p_dev_rec;
   1252   p_dev_rec = btm_find_dev(bd_addr);
   1253   if ((p_dev_rec != NULL) && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)) {
   1254     memcpy(link_key, p_dev_rec->link_key, LINK_KEY_LEN);
   1255     return (BTM_SUCCESS);
   1256   }
   1257   return (BTM_UNKNOWN_ADDR);
   1258 }
   1259 
   1260 /*******************************************************************************
   1261  *
   1262  * Function         BTM_SecGetDeviceLinkKeyType
   1263  *
   1264  * Description      This function is called to obtain link key type for the
   1265  *                  device.
   1266  *                  it returns BTM_SUCCESS if link key is available, or
   1267  *                  BTM_UNKNOWN_ADDR if Security Manager does not know about
   1268  *                  the device or device record does not contain link key info
   1269  *
   1270  * Returns          BTM_LKEY_TYPE_IGNORE if link key is unknown, link type
   1271  *                  otherwise.
   1272  *
   1273  ******************************************************************************/
   1274 tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType(const RawAddress& bd_addr) {
   1275   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
   1276 
   1277   if ((p_dev_rec != NULL) && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)) {
   1278     return p_dev_rec->link_key_type;
   1279   }
   1280   return BTM_LKEY_TYPE_IGNORE;
   1281 }
   1282 
   1283 /*******************************************************************************
   1284  *
   1285  * Function         BTM_SetEncryption
   1286  *
   1287  * Description      This function is called to ensure that connection is
   1288  *                  encrypted.  Should be called only on an open connection.
   1289  *                  Typically only needed for connections that first want to
   1290  *                  bring up unencrypted links, then later encrypt them.
   1291  *
   1292  * Parameters:      bd_addr       - Address of the peer device
   1293  *                  transport     - Link transport
   1294  *                  p_callback    - Pointer to callback function called if
   1295  *                                  this function returns PENDING after required
   1296  *                                  procedures are completed.  Can be set to
   1297  *                                  NULL if status is not desired.
   1298  *                  p_ref_data    - pointer to any data the caller wishes to
   1299  *                                  receive in the callback function upon
   1300  *                                  completion. can be set to NULL if not used.
   1301  *                  sec_act       - LE security action, unused for BR/EDR
   1302  *
   1303  * Returns          BTM_SUCCESS   - already encrypted
   1304  *                  BTM_PENDING   - command will be returned in the callback
   1305  *                  BTM_WRONG_MODE- connection not up.
   1306  *                  BTM_BUSY      - security procedures are currently active
   1307  *                  BTM_MODE_UNSUPPORTED - if security manager not linked in.
   1308  *
   1309  ******************************************************************************/
   1310 tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr,
   1311                               tBT_TRANSPORT transport,
   1312                               tBTM_SEC_CBACK* p_callback, void* p_ref_data,
   1313                               tBTM_BLE_SEC_ACT sec_act) {
   1314   tBTM_STATUS rc = 0;
   1315 
   1316   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
   1317   if (!p_dev_rec || (transport == BT_TRANSPORT_BR_EDR &&
   1318                      p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) ||
   1319       (transport == BT_TRANSPORT_LE &&
   1320        p_dev_rec->ble_hci_handle == BTM_SEC_INVALID_HANDLE)) {
   1321     /* Connection should be up and runnning */
   1322     BTM_TRACE_WARNING("Security Manager: BTM_SetEncryption not connected");
   1323 
   1324     if (p_callback)
   1325       (*p_callback)(&bd_addr, transport, p_ref_data, BTM_WRONG_MODE);
   1326 
   1327     return (BTM_WRONG_MODE);
   1328   }
   1329 
   1330   if (transport == BT_TRANSPORT_BR_EDR &&
   1331       (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED)) {
   1332     BTM_TRACE_EVENT("Security Manager: BTM_SetEncryption already encrypted");
   1333 
   1334     if (*p_callback)
   1335       (*p_callback)(&bd_addr, transport, p_ref_data, BTM_SUCCESS);
   1336 
   1337     return (BTM_SUCCESS);
   1338   }
   1339 
   1340   /* enqueue security request if security is active */
   1341   if (p_dev_rec->p_callback || (p_dev_rec->sec_state != BTM_SEC_STATE_IDLE)) {
   1342     BTM_TRACE_WARNING(
   1343         "Security Manager: BTM_SetEncryption busy, enqueue request");
   1344 
   1345     if (btm_sec_queue_encrypt_request(bd_addr, transport, p_callback,
   1346                                       p_ref_data, sec_act)) {
   1347       return BTM_CMD_STARTED;
   1348     } else {
   1349       if (p_callback)
   1350         (*p_callback)(&bd_addr, transport, p_ref_data, BTM_NO_RESOURCES);
   1351       return BTM_NO_RESOURCES;
   1352     }
   1353   }
   1354 
   1355   p_dev_rec->p_callback = p_callback;
   1356   p_dev_rec->p_ref_data = p_ref_data;
   1357   p_dev_rec->security_required |=
   1358       (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT);
   1359   p_dev_rec->is_originator = false;
   1360 
   1361   BTM_TRACE_API(
   1362       "Security Manager: BTM_SetEncryption Handle:%d State:%d Flags:0x%x "
   1363       "Required:0x%x",
   1364       p_dev_rec->hci_handle, p_dev_rec->sec_state, p_dev_rec->sec_flags,
   1365       p_dev_rec->security_required);
   1366 
   1367   if (transport == BT_TRANSPORT_LE) {
   1368     tACL_CONN* p = btm_bda_to_acl(bd_addr, transport);
   1369     if (p) {
   1370       rc = btm_ble_set_encryption(bd_addr, sec_act, p->link_role);
   1371     } else {
   1372       rc = BTM_WRONG_MODE;
   1373       BTM_TRACE_WARNING("%s: cannot call btm_ble_set_encryption, p is NULL",
   1374                         __func__);
   1375     }
   1376   } else {
   1377     rc = btm_sec_execute_procedure(p_dev_rec);
   1378   }
   1379 
   1380   if (rc != BTM_CMD_STARTED && rc != BTM_BUSY) {
   1381     if (p_callback) {
   1382       p_dev_rec->p_callback = NULL;
   1383       (*p_callback)(&bd_addr, transport, p_dev_rec->p_ref_data, rc);
   1384     }
   1385   }
   1386 
   1387   return (rc);
   1388 }
   1389 
   1390 /*******************************************************************************
   1391  * disconnect the ACL link, if it's not done yet.
   1392  ******************************************************************************/
   1393 static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec,
   1394                                                uint8_t reason,
   1395                                                uint16_t conn_handle) {
   1396   uint8_t old_state = p_dev_rec->sec_state;
   1397   tBTM_STATUS status = BTM_CMD_STARTED;
   1398 
   1399   BTM_TRACE_EVENT("btm_sec_send_hci_disconnect:  handle:0x%x, reason=0x%x",
   1400                   conn_handle, reason);
   1401 
   1402   /* send HCI_Disconnect on a transport only once */
   1403   switch (old_state) {
   1404     case BTM_SEC_STATE_DISCONNECTING:
   1405       if (conn_handle == p_dev_rec->hci_handle) return status;
   1406 
   1407       p_dev_rec->sec_state = BTM_SEC_STATE_DISCONNECTING_BOTH;
   1408       break;
   1409 
   1410     case BTM_SEC_STATE_DISCONNECTING_BLE:
   1411       if (conn_handle == p_dev_rec->ble_hci_handle) return status;
   1412 
   1413       p_dev_rec->sec_state = BTM_SEC_STATE_DISCONNECTING_BOTH;
   1414       break;
   1415 
   1416     case BTM_SEC_STATE_DISCONNECTING_BOTH:
   1417       return status;
   1418 
   1419     default:
   1420       p_dev_rec->sec_state = (conn_handle == p_dev_rec->hci_handle)
   1421                                  ? BTM_SEC_STATE_DISCONNECTING
   1422                                  : BTM_SEC_STATE_DISCONNECTING_BLE;
   1423 
   1424       break;
   1425   }
   1426 
   1427   /* If a role switch is in progress, delay the HCI Disconnect to avoid
   1428    * controller problem */
   1429   if (p_dev_rec->rs_disc_pending == BTM_SEC_RS_PENDING &&
   1430       p_dev_rec->hci_handle == conn_handle) {
   1431     BTM_TRACE_DEBUG(
   1432         "RS in progress - Set DISC Pending flag in btm_sec_send_hci_disconnect "
   1433         "to delay disconnect");
   1434     p_dev_rec->rs_disc_pending = BTM_SEC_DISC_PENDING;
   1435     status = BTM_SUCCESS;
   1436   }
   1437   /* Tear down the HCI link */
   1438   else {
   1439     btsnd_hcic_disconnect(conn_handle, reason);
   1440   }
   1441 
   1442   return status;
   1443 }
   1444 
   1445 /*******************************************************************************
   1446  *
   1447  * Function         BTM_ConfirmReqReply
   1448  *
   1449  * Description      This function is called to confirm the numeric value for
   1450  *                  Simple Pairing in response to BTM_SP_CFM_REQ_EVT
   1451  *
   1452  * Parameters:      res           - result of the operation BTM_SUCCESS if
   1453  *                                  success
   1454  *                  bd_addr       - Address of the peer device
   1455  *
   1456  ******************************************************************************/
   1457 void BTM_ConfirmReqReply(tBTM_STATUS res, const RawAddress& bd_addr) {
   1458   tBTM_SEC_DEV_REC* p_dev_rec;
   1459 
   1460   BTM_TRACE_EVENT("BTM_ConfirmReqReply() State: %s  Res: %u",
   1461                   btm_pair_state_descr(btm_cb.pairing_state), res);
   1462 
   1463   /* If timeout already expired or has been canceled, ignore the reply */
   1464   if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM) ||
   1465       (btm_cb.pairing_bda != bd_addr))
   1466     return;
   1467 
   1468   btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
   1469 
   1470   if ((res == BTM_SUCCESS) || (res == BTM_SUCCESS_NO_SECURITY)) {
   1471     btm_cb.acl_disc_reason = HCI_SUCCESS;
   1472 
   1473     if (res == BTM_SUCCESS) {
   1474       p_dev_rec = btm_find_dev(bd_addr);
   1475       if (p_dev_rec != NULL) {
   1476         p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED;
   1477         p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
   1478       }
   1479     }
   1480 
   1481     btsnd_hcic_user_conf_reply(bd_addr, true);
   1482   } else {
   1483     /* Report authentication failed event from state
   1484      * BTM_PAIR_STATE_WAIT_AUTH_COMPLETE */
   1485     btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
   1486     btsnd_hcic_user_conf_reply(bd_addr, false);
   1487   }
   1488 }
   1489 
   1490 /*******************************************************************************
   1491  *
   1492  * Function         BTM_PasskeyReqReply
   1493  *
   1494  * Description      This function is called to provide the passkey for
   1495  *                  Simple Pairing in response to BTM_SP_KEY_REQ_EVT
   1496  *
   1497  * Parameters:      res     - result of the operation BTM_SUCCESS if success
   1498  *                  bd_addr - Address of the peer device
   1499  *                  passkey - numeric value in the range of
   1500  *                  BTM_MIN_PASSKEY_VAL(0) -
   1501  *                  BTM_MAX_PASSKEY_VAL(999999(0xF423F)).
   1502  *
   1503  ******************************************************************************/
   1504 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
   1505 void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr,
   1506                          uint32_t passkey) {
   1507   BTM_TRACE_API("BTM_PasskeyReqReply: State: %s  res:%d",
   1508                 btm_pair_state_descr(btm_cb.pairing_state), res);
   1509 
   1510   if ((btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) ||
   1511       (btm_cb.pairing_bda != bd_addr)) {
   1512     return;
   1513   }
   1514 
   1515   /* If timeout already expired or has been canceled, ignore the reply */
   1516   if ((btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) &&
   1517       (res != BTM_SUCCESS)) {
   1518     tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
   1519     if (p_dev_rec != NULL) {
   1520       btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
   1521 
   1522       if (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)
   1523         btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE,
   1524                                     p_dev_rec->hci_handle);
   1525       else
   1526         BTM_SecBondCancel(bd_addr);
   1527 
   1528       p_dev_rec->sec_flags &=
   1529           ~(BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_LINK_KEY_KNOWN);
   1530 
   1531       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   1532       return;
   1533     }
   1534   } else if (btm_cb.pairing_state != BTM_PAIR_STATE_KEY_ENTRY)
   1535     return;
   1536 
   1537   if (passkey > BTM_MAX_PASSKEY_VAL) res = BTM_ILLEGAL_VALUE;
   1538 
   1539   btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
   1540 
   1541   if (res != BTM_SUCCESS) {
   1542     /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed
   1543      * event */
   1544     btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
   1545     btsnd_hcic_user_passkey_neg_reply(bd_addr);
   1546   } else {
   1547     btm_cb.acl_disc_reason = HCI_SUCCESS;
   1548     btsnd_hcic_user_passkey_reply(bd_addr, passkey);
   1549   }
   1550 }
   1551 #endif
   1552 
   1553 /*******************************************************************************
   1554  *
   1555  * Function         BTM_SendKeypressNotif
   1556  *
   1557  * Description      This function is used during the passkey entry model
   1558  *                  by a device with KeyboardOnly IO capabilities
   1559  *                  (very likely to be a HID Device).
   1560  *                  It is called by a HID Device to inform the remote device
   1561  *                  when a key has been entered or erased.
   1562  *
   1563  * Parameters:      bd_addr - Address of the peer device
   1564  *                  type - notification type
   1565  *
   1566  ******************************************************************************/
   1567 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
   1568 void BTM_SendKeypressNotif(const RawAddress& bd_addr, tBTM_SP_KEY_TYPE type) {
   1569   /* This API only make sense between PASSKEY_REQ and SP complete */
   1570   if (btm_cb.pairing_state == BTM_PAIR_STATE_KEY_ENTRY)
   1571     btsnd_hcic_send_keypress_notif(bd_addr, type);
   1572 }
   1573 #endif
   1574 
   1575 /*******************************************************************************
   1576  *
   1577  * Function         BTM_IoCapRsp
   1578  *
   1579  * Description      This function is called in response to BTM_SP_IO_REQ_EVT
   1580  *                  When the event data io_req.oob_data is set to
   1581  *                  BTM_OOB_UNKNOWN by the tBTM_SP_CALLBACK implementation,
   1582  *                  this function is called to provide the actual response
   1583  *
   1584  * Parameters:      bd_addr - Address of the peer device
   1585  *                  io_cap  - The IO capability of local device.
   1586  *                  oob     - BTM_OOB_NONE or BTM_OOB_PRESENT.
   1587  *                  auth_req- MITM protection required or not.
   1588  *
   1589  ******************************************************************************/
   1590 void BTM_IoCapRsp(const RawAddress& bd_addr, tBTM_IO_CAP io_cap,
   1591                   tBTM_OOB_DATA oob, tBTM_AUTH_REQ auth_req) {
   1592   BTM_TRACE_EVENT("BTM_IoCapRsp: state: %s  oob: %d io_cap: %d",
   1593                   btm_pair_state_descr(btm_cb.pairing_state), oob, io_cap);
   1594 
   1595   if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS) ||
   1596       (btm_cb.pairing_bda != bd_addr))
   1597     return;
   1598 
   1599   if (oob < BTM_OOB_UNKNOWN && io_cap < BTM_IO_CAP_MAX) {
   1600     btm_cb.devcb.loc_auth_req = auth_req;
   1601     btm_cb.devcb.loc_io_caps = io_cap;
   1602 
   1603     if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
   1604       auth_req = (BTM_AUTH_DD_BOND | (auth_req & BTM_AUTH_YN_BIT));
   1605 
   1606     btsnd_hcic_io_cap_req_reply(bd_addr, io_cap, oob, auth_req);
   1607   }
   1608 }
   1609 
   1610 /*******************************************************************************
   1611  *
   1612  * Function         BTM_ReadLocalOobData
   1613  *
   1614  * Description      This function is called to read the local OOB data from
   1615  *                  LM
   1616  *
   1617  ******************************************************************************/
   1618 void BTM_ReadLocalOobData(void) { btsnd_hcic_read_local_oob_data(); }
   1619 
   1620 /*******************************************************************************
   1621  *
   1622  * Function         BTM_RemoteOobDataReply
   1623  *
   1624  * Description      This function is called to provide the remote OOB data for
   1625  *                  Simple Pairing in response to BTM_SP_RMT_OOB_EVT
   1626  *
   1627  * Parameters:      bd_addr     - Address of the peer device
   1628  *                  c           - simple pairing Hash C.
   1629  *                  r           - simple pairing Randomizer  C.
   1630  *
   1631  ******************************************************************************/
   1632 void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr,
   1633                             BT_OCTET16 c, BT_OCTET16 r) {
   1634   BTM_TRACE_EVENT("%s() - State: %s res: %d", __func__,
   1635                   btm_pair_state_descr(btm_cb.pairing_state), res);
   1636 
   1637   /* If timeout already expired or has been canceled, ignore the reply */
   1638   if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP) return;
   1639 
   1640   btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
   1641 
   1642   if (res != BTM_SUCCESS) {
   1643     /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed
   1644      * event */
   1645     btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
   1646     btsnd_hcic_rem_oob_neg_reply(bd_addr);
   1647   } else {
   1648     btm_cb.acl_disc_reason = HCI_SUCCESS;
   1649     btsnd_hcic_rem_oob_reply(bd_addr, c, r);
   1650   }
   1651 }
   1652 
   1653 /*******************************************************************************
   1654  *
   1655  * Function         BTM_BuildOobData
   1656  *
   1657  * Description      This function is called to build the OOB data payload to
   1658  *                  be sent over OOB (non-Bluetooth) link
   1659  *
   1660  * Parameters:      p_data  - the location for OOB data
   1661  *                  max_len - p_data size.
   1662  *                  c       - simple pairing Hash C.
   1663  *                  r       - simple pairing Randomizer  C.
   1664  *                  name_len- 0, local device name would not be included.
   1665  *                            otherwise, the local device name is included for
   1666  *                            up to this specified length
   1667  *
   1668  * Returns          Number of bytes in p_data.
   1669  *
   1670  ******************************************************************************/
   1671 uint16_t BTM_BuildOobData(uint8_t* p_data, uint16_t max_len, BT_OCTET16 c,
   1672                           BT_OCTET16 r, uint8_t name_len) {
   1673   uint8_t* p = p_data;
   1674   uint16_t len = 0;
   1675   uint16_t name_size;
   1676   uint8_t name_type = BTM_EIR_SHORTENED_LOCAL_NAME_TYPE;
   1677 
   1678   if (p_data && max_len >= BTM_OOB_MANDATORY_SIZE) {
   1679     /* add mandatory part */
   1680     UINT16_TO_STREAM(p, len);
   1681     BDADDR_TO_STREAM(p, *controller_get_interface()->get_address());
   1682 
   1683     len = BTM_OOB_MANDATORY_SIZE;
   1684     max_len -= len;
   1685 
   1686     /* now optional part */
   1687 
   1688     /* add Hash C */
   1689     uint16_t delta = BTM_OOB_HASH_C_SIZE + 2;
   1690     if (max_len >= delta) {
   1691       *p++ = BTM_OOB_HASH_C_SIZE + 1;
   1692       *p++ = BTM_EIR_OOB_SSP_HASH_C_TYPE;
   1693       ARRAY_TO_STREAM(p, c, BTM_OOB_HASH_C_SIZE);
   1694       len += delta;
   1695       max_len -= delta;
   1696     }
   1697 
   1698     /* add Rand R */
   1699     delta = BTM_OOB_RAND_R_SIZE + 2;
   1700     if (max_len >= delta) {
   1701       *p++ = BTM_OOB_RAND_R_SIZE + 1;
   1702       *p++ = BTM_EIR_OOB_SSP_RAND_R_TYPE;
   1703       ARRAY_TO_STREAM(p, r, BTM_OOB_RAND_R_SIZE);
   1704       len += delta;
   1705       max_len -= delta;
   1706     }
   1707 
   1708     /* add class of device */
   1709     delta = BTM_OOB_COD_SIZE + 2;
   1710     if (max_len >= delta) {
   1711       *p++ = BTM_OOB_COD_SIZE + 1;
   1712       *p++ = BTM_EIR_OOB_COD_TYPE;
   1713       DEVCLASS_TO_STREAM(p, btm_cb.devcb.dev_class);
   1714       len += delta;
   1715       max_len -= delta;
   1716     }
   1717     name_size = name_len;
   1718     if (name_size > strlen(btm_cb.cfg.bd_name)) {
   1719       name_type = BTM_EIR_COMPLETE_LOCAL_NAME_TYPE;
   1720       name_size = (uint16_t)strlen(btm_cb.cfg.bd_name);
   1721     }
   1722     delta = name_size + 2;
   1723     if (max_len >= delta) {
   1724       *p++ = name_size + 1;
   1725       *p++ = name_type;
   1726       ARRAY_TO_STREAM(p, btm_cb.cfg.bd_name, name_size);
   1727       len += delta;
   1728       max_len -= delta;
   1729     }
   1730     /* update len */
   1731     p = p_data;
   1732     UINT16_TO_STREAM(p, len);
   1733   }
   1734   return len;
   1735 }
   1736 
   1737 /*******************************************************************************
   1738  *
   1739  * Function         BTM_BothEndsSupportSecureConnections
   1740  *
   1741  * Description      This function is called to check if both the local device
   1742  *                  and the peer device specified by bd_addr support BR/EDR
   1743  *                  Secure Connections.
   1744  *
   1745  * Parameters:      bd_addr - address of the peer
   1746  *
   1747  * Returns          true if BR/EDR Secure Connections are supported by both
   1748  *                  local and the remote device, else false.
   1749  *
   1750  ******************************************************************************/
   1751 bool BTM_BothEndsSupportSecureConnections(const RawAddress& bd_addr) {
   1752   return ((controller_get_interface()->supports_secure_connections()) &&
   1753           (BTM_PeerSupportsSecureConnections(bd_addr)));
   1754 }
   1755 
   1756 /*******************************************************************************
   1757  *
   1758  * Function         BTM_PeerSupportsSecureConnections
   1759  *
   1760  * Description      This function is called to check if the peer supports
   1761  *                  BR/EDR Secure Connections.
   1762  *
   1763  * Parameters:      bd_addr - address of the peer
   1764  *
   1765  * Returns          true if BR/EDR Secure Connections are supported by the peer,
   1766  *                  else false.
   1767  *
   1768  ******************************************************************************/
   1769 bool BTM_PeerSupportsSecureConnections(const RawAddress& bd_addr) {
   1770   tBTM_SEC_DEV_REC* p_dev_rec;
   1771 
   1772   p_dev_rec = btm_find_dev(bd_addr);
   1773   if (p_dev_rec == NULL) {
   1774     LOG(WARNING) << __func__ << ": unknown BDA: " << bd_addr;
   1775     return false;
   1776   }
   1777 
   1778   return (p_dev_rec->remote_supports_secure_connections);
   1779 }
   1780 
   1781 /*******************************************************************************
   1782  *
   1783  * Function         BTM_ReadOobData
   1784  *
   1785  * Description      This function is called to parse the OOB data payload
   1786  *                  received over OOB (non-Bluetooth) link
   1787  *
   1788  * Parameters:      p_data  - the location for OOB data
   1789  *                  eir_tag - The associated EIR tag to read the data.
   1790  *                  *p_len(output) - the length of the data with the given tag.
   1791  *
   1792  * Returns          the beginning of the data with the given tag.
   1793  *                  NULL, if the tag is not found.
   1794  *
   1795  ******************************************************************************/
   1796 uint8_t* BTM_ReadOobData(uint8_t* p_data, uint8_t eir_tag, uint8_t* p_len) {
   1797   uint8_t* p = p_data;
   1798   uint16_t max_len;
   1799   uint8_t len, type;
   1800   uint8_t* p_ret = NULL;
   1801   uint8_t ret_len = 0;
   1802 
   1803   if (p_data) {
   1804     STREAM_TO_UINT16(max_len, p);
   1805     if (max_len >= BTM_OOB_MANDATORY_SIZE) {
   1806       if (BTM_EIR_OOB_BD_ADDR_TYPE == eir_tag) {
   1807         p_ret = p; /* the location for bd_addr */
   1808         ret_len = BTM_OOB_BD_ADDR_SIZE;
   1809       } else {
   1810         p += BD_ADDR_LEN;
   1811         max_len -= BTM_OOB_MANDATORY_SIZE;
   1812         /* now the optional data in EIR format */
   1813         while (max_len > 0) {
   1814           len = *p++; /* tag data len + 1 */
   1815           type = *p++;
   1816           if (eir_tag == type) {
   1817             p_ret = p;
   1818             ret_len = len - 1;
   1819             break;
   1820           }
   1821           /* the data size of this tag is len + 1 (tag data len + 2) */
   1822           if (max_len > len) {
   1823             max_len -= len;
   1824             max_len--;
   1825             len--;
   1826             p += len;
   1827           } else
   1828             max_len = 0;
   1829         }
   1830       }
   1831     }
   1832   }
   1833 
   1834   if (p_len) *p_len = ret_len;
   1835 
   1836   return p_ret;
   1837 }
   1838 
   1839 /*******************************************************************************
   1840  *
   1841  * Function         BTM_SetOutService
   1842  *
   1843  * Description      This function is called to set the service for
   1844  *                  outgoing connections.
   1845  *
   1846  *                  If the profile/application calls BTM_SetSecurityLevel
   1847  *                  before initiating a connection, this function does not
   1848  *                  need to be called.
   1849  *
   1850  * Returns          void
   1851  *
   1852  ******************************************************************************/
   1853 void BTM_SetOutService(const RawAddress& bd_addr, uint8_t service_id,
   1854                        uint32_t mx_chan_id) {
   1855   tBTM_SEC_DEV_REC* p_dev_rec;
   1856   tBTM_SEC_SERV_REC* p_serv_rec = &btm_cb.sec_serv_rec[0];
   1857 
   1858   btm_cb.p_out_serv = p_serv_rec;
   1859   p_dev_rec = btm_find_dev(bd_addr);
   1860 
   1861   for (int i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) {
   1862     if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) &&
   1863         (p_serv_rec->service_id == service_id) &&
   1864         (p_serv_rec->orig_mx_chan_id == mx_chan_id)) {
   1865       BTM_TRACE_API(
   1866           "BTM_SetOutService p_out_serv id %d, psm 0x%04x, proto_id %d, "
   1867           "chan_id %d",
   1868           p_serv_rec->service_id, p_serv_rec->psm, p_serv_rec->mx_proto_id,
   1869           p_serv_rec->orig_mx_chan_id);
   1870       btm_cb.p_out_serv = p_serv_rec;
   1871       if (p_dev_rec) p_dev_rec->p_cur_service = p_serv_rec;
   1872       break;
   1873     }
   1874   }
   1875 }
   1876 
   1877 /************************************************************************
   1878  *              I N T E R N A L     F U N C T I O N S
   1879  ************************************************************************/
   1880 /*******************************************************************************
   1881  *
   1882  * Function         btm_sec_is_upgrade_possible
   1883  *
   1884  * Description      This function returns true if the existing link key
   1885  *                  can be upgraded or if the link key does not exist.
   1886  *
   1887  * Returns          bool
   1888  *
   1889  ******************************************************************************/
   1890 static bool btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC* p_dev_rec,
   1891                                         bool is_originator) {
   1892   uint16_t mtm_check = is_originator ? BTM_SEC_OUT_MITM : BTM_SEC_IN_MITM;
   1893   bool is_possible = true;
   1894 
   1895   if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) {
   1896     is_possible = false;
   1897     if (p_dev_rec->p_cur_service) {
   1898       BTM_TRACE_DEBUG(
   1899           "%s() id: %d, link_key_typet: %d, rmt_io_caps: %d, chk flags: 0x%x, "
   1900           "flags: 0x%x",
   1901           __func__, p_dev_rec->p_cur_service->service_id,
   1902           p_dev_rec->link_key_type, p_dev_rec->rmt_io_caps, mtm_check,
   1903           p_dev_rec->p_cur_service->security_flags);
   1904     } else {
   1905       BTM_TRACE_DEBUG(
   1906           "%s() link_key_typet: %d, rmt_io_caps: %d, chk flags: 0x%x", __func__,
   1907           p_dev_rec->link_key_type, p_dev_rec->rmt_io_caps, mtm_check);
   1908     }
   1909     /* Already have a link key to the connected peer. Is the link key secure
   1910      *enough?
   1911      ** Is a link key upgrade even possible?
   1912      */
   1913     if ((p_dev_rec->security_required & mtm_check) /* needs MITM */
   1914         && ((p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB) ||
   1915             (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256))
   1916         /* has unauthenticated
   1917         link key */
   1918         && (p_dev_rec->rmt_io_caps < BTM_IO_CAP_MAX) /* a valid peer IO cap */
   1919         && (btm_sec_io_map[p_dev_rec->rmt_io_caps][btm_cb.devcb.loc_io_caps]))
   1920     /* authenticated
   1921     link key is possible */
   1922     {
   1923       /* upgrade is possible: check if the application wants the upgrade.
   1924        * If the application is configured to use a global MITM flag,
   1925        * it probably would not want to upgrade the link key based on the
   1926        * security level database */
   1927       is_possible = true;
   1928     }
   1929   }
   1930   BTM_TRACE_DEBUG("%s() is_possible: %d sec_flags: 0x%x", __func__, is_possible,
   1931                   p_dev_rec->sec_flags);
   1932   return is_possible;
   1933 }
   1934 
   1935 /*******************************************************************************
   1936  *
   1937  * Function         btm_sec_check_upgrade
   1938  *
   1939  * Description      This function is called to check if the existing link key
   1940  *                  needs to be upgraded.
   1941  *
   1942  * Returns          void
   1943  *
   1944  ******************************************************************************/
   1945 static void btm_sec_check_upgrade(tBTM_SEC_DEV_REC* p_dev_rec,
   1946                                   bool is_originator) {
   1947   BTM_TRACE_DEBUG("%s()", __func__);
   1948 
   1949   /* Only check if link key already exists */
   1950   if (!(p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)) return;
   1951 
   1952   if (btm_sec_is_upgrade_possible(p_dev_rec, is_originator) == true) {
   1953     BTM_TRACE_DEBUG("need upgrade!! sec_flags:0x%x", p_dev_rec->sec_flags);
   1954     /* upgrade is possible: check if the application wants the upgrade.
   1955      * If the application is configured to use a global MITM flag,
   1956      * it probably would not want to upgrade the link key based on the security
   1957      * level database */
   1958     tBTM_SP_UPGRADE evt_data;
   1959     evt_data.bd_addr = p_dev_rec->bd_addr;
   1960     evt_data.upgrade = true;
   1961     if (btm_cb.api.p_sp_callback)
   1962       (*btm_cb.api.p_sp_callback)(BTM_SP_UPGRADE_EVT,
   1963                                   (tBTM_SP_EVT_DATA*)&evt_data);
   1964 
   1965     BTM_TRACE_DEBUG("evt_data.upgrade:0x%x", evt_data.upgrade);
   1966     if (evt_data.upgrade) {
   1967       /* if the application confirms the upgrade, set the upgrade bit */
   1968       p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
   1969 
   1970       /* Clear the link key known to go through authentication/pairing again */
   1971       p_dev_rec->sec_flags &=
   1972           ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED);
   1973       p_dev_rec->sec_flags &= ~BTM_SEC_AUTHENTICATED;
   1974       BTM_TRACE_DEBUG("sec_flags:0x%x", p_dev_rec->sec_flags);
   1975     }
   1976   }
   1977 }
   1978 
   1979 /*******************************************************************************
   1980  *
   1981  * Function         btm_sec_l2cap_access_req
   1982  *
   1983  * Description      This function is called by the L2CAP to grant permission to
   1984  *                  establish L2CAP connection to or from the peer device.
   1985  *
   1986  * Parameters:      bd_addr       - Address of the peer device
   1987  *                  psm           - L2CAP PSM
   1988  *                  is_originator - true if protocol above L2CAP originates
   1989  *                                  connection
   1990  *                  p_callback    - Pointer to callback function called if
   1991  *                                  this function returns PENDING after required
   1992  *                                  procedures are complete. MUST NOT BE NULL.
   1993  *
   1994  * Returns          tBTM_STATUS
   1995  *
   1996  ******************************************************************************/
   1997 tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm,
   1998                                      uint16_t handle, CONNECTION_TYPE conn_type,
   1999                                      tBTM_SEC_CALLBACK* p_callback,
   2000                                      void* p_ref_data) {
   2001   tBTM_SEC_DEV_REC* p_dev_rec;
   2002   tBTM_SEC_SERV_REC* p_serv_rec;
   2003   uint16_t security_required;
   2004   uint16_t old_security_required;
   2005   bool old_is_originator;
   2006   tBTM_STATUS rc = BTM_SUCCESS;
   2007   bool chk_acp_auth_done = false;
   2008   bool is_originator;
   2009   tBT_TRANSPORT transport =
   2010       BT_TRANSPORT_BR_EDR; /* should check PSM range in LE connection oriented
   2011                               L2CAP connection */
   2012 
   2013 #if (L2CAP_UCD_INCLUDED == TRUE)
   2014   if (conn_type & CONNECTION_TYPE_ORIG_MASK)
   2015     is_originator = true;
   2016   else
   2017     is_originator = false;
   2018 
   2019   BTM_TRACE_DEBUG("%s() conn_type: 0x%x, 0x%x", __func__, conn_type,
   2020                   p_ref_data);
   2021 #else
   2022   is_originator = conn_type;
   2023 
   2024   BTM_TRACE_DEBUG("%s() is_originator:%d, 0x%x", __func__, is_originator,
   2025                   p_ref_data);
   2026 #endif
   2027 
   2028   /* Find or get oldest record */
   2029   p_dev_rec = btm_find_or_alloc_dev(bd_addr);
   2030 
   2031   p_dev_rec->hci_handle = handle;
   2032 
   2033   /* Find the service record for the PSM */
   2034   p_serv_rec = btm_sec_find_first_serv(conn_type, psm);
   2035 
   2036   /* If there is no application registered with this PSM do not allow connection
   2037    */
   2038   if (!p_serv_rec) {
   2039     BTM_TRACE_WARNING("%s() PSM: %d no application registerd", __func__, psm);
   2040     (*p_callback)(&bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED);
   2041     return (BTM_MODE_UNSUPPORTED);
   2042   }
   2043 
   2044   /* Services level0 by default have no security */
   2045   if ((btm_sec_is_serv_level0(psm)) &&
   2046       (!btm_cb.devcb.secure_connections_only)) {
   2047     (*p_callback)(&bd_addr, transport, p_ref_data, BTM_SUCCESS_NO_SECURITY);
   2048     return (BTM_SUCCESS);
   2049   }
   2050 #if (L2CAP_UCD_INCLUDED == TRUE)
   2051   if (conn_type & CONNECTION_TYPE_CONNLESS_MASK) {
   2052     if (btm_cb.security_mode == BTM_SEC_MODE_SC) {
   2053       security_required = btm_sec_set_serv_level4_flags(
   2054           p_serv_rec->ucd_security_flags, is_originator);
   2055     } else {
   2056       security_required = p_serv_rec->ucd_security_flags;
   2057     }
   2058 
   2059     rc = BTM_CMD_STARTED;
   2060     if (is_originator) {
   2061       if (((security_required & BTM_SEC_OUT_FLAGS) == 0) ||
   2062           ((((security_required & BTM_SEC_OUT_FLAGS) ==
   2063              BTM_SEC_OUT_AUTHENTICATE) &&
   2064             (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))) ||
   2065           ((((security_required & BTM_SEC_OUT_FLAGS) ==
   2066              (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) &&
   2067             (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED))) ||
   2068           ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_FLAGS) &&
   2069             (p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED)))) {
   2070         rc = BTM_SUCCESS;
   2071       }
   2072     } else {
   2073       if (((security_required & BTM_SEC_IN_FLAGS) == 0) ||
   2074           ((((security_required & BTM_SEC_IN_FLAGS) ==
   2075              BTM_SEC_IN_AUTHENTICATE) &&
   2076             (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))) ||
   2077           ((((security_required & BTM_SEC_IN_FLAGS) ==
   2078              (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) &&
   2079             (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED))) ||
   2080           ((((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_FLAGS) &&
   2081             (p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED)))) {
   2082         // Check for 16 digits (or MITM)
   2083         if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) ||
   2084             (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) ==
   2085               BTM_SEC_IN_MIN_16_DIGIT_PIN) &&
   2086              btm_dev_16_digit_authenticated(p_dev_rec))) {
   2087           rc = BTM_SUCCESS;
   2088         }
   2089       }
   2090     }
   2091 
   2092     if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) &&
   2093         (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   2094       rc = BTM_CMD_STARTED;
   2095     }
   2096 
   2097     if (rc == BTM_SUCCESS) {
   2098       if (p_callback)
   2099         (*p_callback)(&bd_addr, transport, (void*)p_ref_data, BTM_SUCCESS);
   2100 
   2101       return (BTM_SUCCESS);
   2102     }
   2103   } else
   2104 #endif
   2105   {
   2106     if (btm_cb.security_mode == BTM_SEC_MODE_SC) {
   2107       security_required = btm_sec_set_serv_level4_flags(
   2108           p_serv_rec->security_flags, is_originator);
   2109     } else {
   2110       security_required = p_serv_rec->security_flags;
   2111     }
   2112   }
   2113 
   2114   BTM_TRACE_DEBUG(
   2115       "%s: security_required 0x%04x, is_originator 0x%02x, psm  0x%04x",
   2116       __func__, security_required, is_originator, psm);
   2117 
   2118   if ((!is_originator) && (security_required & BTM_SEC_MODE4_LEVEL4)) {
   2119     bool local_supports_sc =
   2120         controller_get_interface()->supports_secure_connections();
   2121     /* acceptor receives L2CAP Channel Connect Request for Secure Connections
   2122      * Only service */
   2123     if (!(local_supports_sc) ||
   2124         !(p_dev_rec->remote_supports_secure_connections)) {
   2125       BTM_TRACE_DEBUG("%s: SC only service, local_support_for_sc %d",
   2126                       "rmt_support_for_sc : %d -> fail pairing", __func__,
   2127                       local_supports_sc,
   2128                       p_dev_rec->remote_supports_secure_connections);
   2129       if (p_callback)
   2130         (*p_callback)(&bd_addr, transport, (void*)p_ref_data,
   2131                       BTM_MODE4_LEVEL4_NOT_SUPPORTED);
   2132 
   2133       return (BTM_MODE4_LEVEL4_NOT_SUPPORTED);
   2134     }
   2135   }
   2136 
   2137   /* there are some devices (moto KRZR) which connects to several services at
   2138    * the same time */
   2139   /* we will process one after another */
   2140   if ((p_dev_rec->p_callback) ||
   2141       (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)) {
   2142     BTM_TRACE_EVENT("%s() - busy - PSM:%d delayed  state: %s mode:%d, sm4:0x%x",
   2143                     __func__, psm, btm_pair_state_descr(btm_cb.pairing_state),
   2144                     btm_cb.security_mode, p_dev_rec->sm4);
   2145     BTM_TRACE_EVENT("security_flags:x%x, sec_flags:x%x", security_required,
   2146                     p_dev_rec->sec_flags);
   2147     rc = BTM_CMD_STARTED;
   2148     if ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED ||
   2149          btm_cb.security_mode == BTM_SEC_MODE_NONE ||
   2150          btm_cb.security_mode == BTM_SEC_MODE_SERVICE ||
   2151          btm_cb.security_mode == BTM_SEC_MODE_LINK) ||
   2152         (BTM_SM4_KNOWN == p_dev_rec->sm4) ||
   2153         (BTM_SEC_IS_SM4(p_dev_rec->sm4) &&
   2154          (btm_sec_is_upgrade_possible(p_dev_rec, is_originator) == false))) {
   2155       /* legacy mode - local is legacy or local is lisbon/peer is legacy
   2156        * or SM4 with no possibility of link key upgrade */
   2157       if (is_originator) {
   2158         if (((security_required & BTM_SEC_OUT_FLAGS) == 0) ||
   2159             ((((security_required & BTM_SEC_OUT_FLAGS) ==
   2160                BTM_SEC_OUT_AUTHENTICATE) &&
   2161               btm_dev_authenticated(p_dev_rec))) ||
   2162             ((((security_required & BTM_SEC_OUT_FLAGS) ==
   2163                (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) &&
   2164               btm_dev_encrypted(p_dev_rec))) ||
   2165             ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_FLAGS) &&
   2166               btm_dev_authorized(p_dev_rec) && btm_dev_encrypted(p_dev_rec)))) {
   2167           rc = BTM_SUCCESS;
   2168         }
   2169       } else {
   2170         if (((security_required & BTM_SEC_IN_FLAGS) == 0) ||
   2171             (((security_required & BTM_SEC_IN_FLAGS) ==
   2172               BTM_SEC_IN_AUTHENTICATE) &&
   2173              btm_dev_authenticated(p_dev_rec)) ||
   2174             (((security_required & BTM_SEC_IN_FLAGS) ==
   2175               (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) &&
   2176              btm_dev_encrypted(p_dev_rec)) ||
   2177             (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHORIZE) &&
   2178              (btm_dev_authorized(p_dev_rec) ||
   2179               btm_serv_trusted(p_dev_rec, p_serv_rec))) ||
   2180             (((security_required & BTM_SEC_IN_FLAGS) ==
   2181               (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_AUTHORIZE)) &&
   2182              ((btm_dev_authorized(p_dev_rec) ||
   2183                btm_serv_trusted(p_dev_rec, p_serv_rec)) &&
   2184               btm_dev_authenticated(p_dev_rec))) ||
   2185             (((security_required & BTM_SEC_IN_FLAGS) ==
   2186               (BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHORIZE)) &&
   2187              ((btm_dev_authorized(p_dev_rec) ||
   2188                btm_serv_trusted(p_dev_rec, p_serv_rec)) &&
   2189               btm_dev_encrypted(p_dev_rec))) ||
   2190             (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_FLAGS) &&
   2191              btm_dev_encrypted(p_dev_rec) &&
   2192              (btm_dev_authorized(p_dev_rec) ||
   2193               btm_serv_trusted(p_dev_rec, p_serv_rec)))) {
   2194           // Check for 16 digits (or MITM)
   2195           if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) ||
   2196               (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) ==
   2197                 BTM_SEC_IN_MIN_16_DIGIT_PIN) &&
   2198                btm_dev_16_digit_authenticated(p_dev_rec))) {
   2199             rc = BTM_SUCCESS;
   2200           }
   2201         }
   2202       }
   2203 
   2204       if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) &&
   2205           (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   2206         rc = BTM_CMD_STARTED;
   2207       }
   2208 
   2209       if (rc == BTM_SUCCESS) {
   2210         if (p_callback)
   2211           (*p_callback)(&bd_addr, transport, (void*)p_ref_data, BTM_SUCCESS);
   2212         return (BTM_SUCCESS);
   2213       }
   2214     }
   2215 
   2216     btm_cb.sec_req_pending = true;
   2217     return (BTM_CMD_STARTED);
   2218   }
   2219 
   2220   /* Save pointer to service record */
   2221   p_dev_rec->p_cur_service = p_serv_rec;
   2222 
   2223   /* Modify security_required in btm_sec_l2cap_access_req for Lisbon */
   2224   if (btm_cb.security_mode == BTM_SEC_MODE_SP ||
   2225       btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
   2226       btm_cb.security_mode == BTM_SEC_MODE_SC) {
   2227     if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
   2228       if (is_originator) {
   2229         /* SM4 to SM4 -> always authenticate & encrypt */
   2230         security_required |= (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT);
   2231       } else /* acceptor */
   2232       {
   2233         /* SM4 to SM4: the acceptor needs to make sure the authentication is
   2234          * already done */
   2235         chk_acp_auth_done = true;
   2236         /* SM4 to SM4 -> always authenticate & encrypt */
   2237         security_required |= (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT);
   2238       }
   2239     } else if (!(BTM_SM4_KNOWN & p_dev_rec->sm4)) {
   2240       /* the remote features are not known yet */
   2241       BTM_TRACE_DEBUG("%s: (%s) remote features unknown!!sec_flags:0x%02x",
   2242                       __func__, (is_originator) ? "initiator" : "acceptor",
   2243                       p_dev_rec->sec_flags);
   2244 
   2245       p_dev_rec->sm4 |= BTM_SM4_REQ_PEND;
   2246       return (BTM_CMD_STARTED);
   2247     }
   2248   }
   2249 
   2250   BTM_TRACE_DEBUG(
   2251       "%s()  sm4:0x%x, sec_flags:0x%x, security_required:0x%x chk:%d", __func__,
   2252       p_dev_rec->sm4, p_dev_rec->sec_flags, security_required,
   2253       chk_acp_auth_done);
   2254 
   2255   old_security_required = p_dev_rec->security_required;
   2256   old_is_originator = p_dev_rec->is_originator;
   2257   p_dev_rec->security_required = security_required;
   2258   p_dev_rec->p_ref_data = p_ref_data;
   2259   p_dev_rec->is_originator = is_originator;
   2260 
   2261 #if (L2CAP_UCD_INCLUDED == TRUE)
   2262   if (conn_type & CONNECTION_TYPE_CONNLESS_MASK)
   2263     p_dev_rec->is_ucd = true;
   2264   else
   2265     p_dev_rec->is_ucd = false;
   2266 #endif
   2267 
   2268 /* If there are multiple service records used through the same PSM */
   2269 /* leave security decision for the multiplexor on the top */
   2270 #if (L2CAP_UCD_INCLUDED == TRUE)
   2271   if (((btm_sec_find_next_serv(p_serv_rec)) != NULL) &&
   2272       (!(conn_type & CONNECTION_TYPE_CONNLESS_MASK))) /* if not UCD */
   2273 #else
   2274   if ((btm_sec_find_next_serv(p_serv_rec)) != NULL)
   2275 #endif
   2276   {
   2277     BTM_TRACE_DEBUG("no next_serv sm4:0x%x, chk:%d", p_dev_rec->sm4,
   2278                     chk_acp_auth_done);
   2279     if (!BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
   2280       BTM_TRACE_EVENT(
   2281           "Security Manager: l2cap_access_req PSM:%d postponed for multiplexer",
   2282           psm);
   2283       /* pre-Lisbon: restore the old settings */
   2284       p_dev_rec->security_required = old_security_required;
   2285       p_dev_rec->is_originator = old_is_originator;
   2286 
   2287       (*p_callback)(&bd_addr, transport, p_ref_data, BTM_SUCCESS);
   2288 
   2289       return (BTM_SUCCESS);
   2290     }
   2291   }
   2292 
   2293   /* if the originator is using dynamic PSM in legacy mode, do not start any
   2294    * security process now
   2295    * The layer above L2CAP needs to carry out the security requirement after
   2296    * L2CAP connect
   2297    * response is received */
   2298   if (is_originator && ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED ||
   2299                          btm_cb.security_mode == BTM_SEC_MODE_NONE ||
   2300                          btm_cb.security_mode == BTM_SEC_MODE_SERVICE ||
   2301                          btm_cb.security_mode == BTM_SEC_MODE_LINK) ||
   2302                         !BTM_SEC_IS_SM4(p_dev_rec->sm4)) &&
   2303       (psm >= 0x1001)) {
   2304     BTM_TRACE_EVENT(
   2305         "dynamic PSM:0x%x in legacy mode - postponed for upper layer", psm);
   2306     /* restore the old settings */
   2307     p_dev_rec->security_required = old_security_required;
   2308     p_dev_rec->is_originator = old_is_originator;
   2309 
   2310     (*p_callback)(&bd_addr, transport, p_ref_data, BTM_SUCCESS);
   2311 
   2312     return (BTM_SUCCESS);
   2313   }
   2314 
   2315   if (chk_acp_auth_done) {
   2316     BTM_TRACE_DEBUG(
   2317         "(SM4 to SM4) btm_sec_l2cap_access_req rspd. authenticated: x%x, enc: "
   2318         "x%x",
   2319         (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED),
   2320         (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED));
   2321     /* SM4, but we do not know for sure which level of security we need.
   2322      * as long as we have a link key, it's OK */
   2323     if ((0 == (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) ||
   2324         (0 == (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED))) {
   2325       rc = BTM_DELAY_CHECK;
   2326       /*
   2327       2046 may report HCI_Encryption_Change and L2C Connection Request out of
   2328       sequence
   2329       because of data path issues. Delay this disconnect a little bit
   2330       */
   2331       LOG_INFO(
   2332           LOG_TAG,
   2333           "%s peer should have initiated security process by now (SM4 to SM4)",
   2334           __func__);
   2335       p_dev_rec->p_callback = p_callback;
   2336       p_dev_rec->sec_state = BTM_SEC_STATE_DELAY_FOR_ENC;
   2337       (*p_callback)(&bd_addr, transport, p_ref_data, rc);
   2338 
   2339       return BTM_SUCCESS;
   2340     }
   2341   }
   2342 
   2343   p_dev_rec->p_callback = p_callback;
   2344 
   2345   if (p_dev_rec->last_author_service_id == BTM_SEC_NO_LAST_SERVICE_ID ||
   2346       p_dev_rec->last_author_service_id !=
   2347           p_dev_rec->p_cur_service->service_id) {
   2348     /* Although authentication and encryption are per connection
   2349     ** authorization is per access request.  For example when serial connection
   2350     ** is up and authorized and client requests to read file (access to other
   2351     ** scn), we need to request user's permission again.
   2352     */
   2353     p_dev_rec->sec_flags &= ~BTM_SEC_AUTHORIZED;
   2354   }
   2355 
   2356   if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
   2357     if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) &&
   2358         (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   2359       /* BTM_LKEY_TYPE_AUTH_COMB_P_256 is the only acceptable key in this case
   2360        */
   2361       if ((p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) != 0) {
   2362         p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
   2363       }
   2364       p_dev_rec->sec_flags &=
   2365           ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
   2366             BTM_SEC_AUTHENTICATED);
   2367       BTM_TRACE_DEBUG("%s: sec_flags:0x%x", __func__, p_dev_rec->sec_flags);
   2368     } else {
   2369       /* If we already have a link key to the connected peer, is it secure
   2370        * enough? */
   2371       btm_sec_check_upgrade(p_dev_rec, is_originator);
   2372     }
   2373   }
   2374 
   2375   BTM_TRACE_EVENT(
   2376       "%s() PSM:%d Handle:%d State:%d Flags: 0x%x Required: 0x%x Service ID:%d",
   2377       __func__, psm, handle, p_dev_rec->sec_state, p_dev_rec->sec_flags,
   2378       p_dev_rec->security_required, p_dev_rec->p_cur_service->service_id);
   2379 
   2380   rc = btm_sec_execute_procedure(p_dev_rec);
   2381   if (rc != BTM_CMD_STARTED) {
   2382     p_dev_rec->p_callback = NULL;
   2383     (*p_callback)(&bd_addr, transport, p_dev_rec->p_ref_data, (uint8_t)rc);
   2384   }
   2385 
   2386   return (rc);
   2387 }
   2388 
   2389 /*******************************************************************************
   2390  *
   2391  * Function         btm_sec_mx_access_request
   2392  *
   2393  * Description      This function is called by all Multiplexing Protocols during
   2394  *                  establishing connection to or from peer device to grant
   2395  *                  permission to establish application connection.
   2396  *
   2397  * Parameters:      bd_addr       - Address of the peer device
   2398  *                  psm           - L2CAP PSM
   2399  *                  is_originator - true if protocol above L2CAP originates
   2400  *                                  connection
   2401  *                  mx_proto_id   - protocol ID of the multiplexer
   2402  *                  mx_chan_id    - multiplexer channel to reach application
   2403  *                  p_callback    - Pointer to callback function called if
   2404  *                                  this function returns PENDING after required
   2405  *                                  procedures are completed
   2406  *                  p_ref_data    - Pointer to any reference data needed by the
   2407  *                                  the callback function.
   2408  *
   2409  * Returns          BTM_CMD_STARTED
   2410  *
   2411  ******************************************************************************/
   2412 tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, uint16_t psm,
   2413                                       bool is_originator, uint32_t mx_proto_id,
   2414                                       uint32_t mx_chan_id,
   2415                                       tBTM_SEC_CALLBACK* p_callback,
   2416                                       void* p_ref_data) {
   2417   tBTM_SEC_DEV_REC* p_dev_rec;
   2418   tBTM_SEC_SERV_REC* p_serv_rec;
   2419   tBTM_STATUS rc;
   2420   uint16_t security_required;
   2421   bool transport = false; /* should check PSM range in LE connection oriented
   2422                              L2CAP connection */
   2423 
   2424   BTM_TRACE_DEBUG("%s() is_originator: %d", __func__, is_originator);
   2425   /* Find or get oldest record */
   2426   p_dev_rec = btm_find_or_alloc_dev(bd_addr);
   2427 
   2428   /* Find the service record for the PSM */
   2429   p_serv_rec =
   2430       btm_sec_find_mx_serv(is_originator, psm, mx_proto_id, mx_chan_id);
   2431 
   2432   /* If there is no application registered with this PSM do not allow connection
   2433    */
   2434   if (!p_serv_rec) {
   2435     if (p_callback)
   2436       (*p_callback)(&bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED);
   2437 
   2438     BTM_TRACE_ERROR(
   2439         "Security Manager: MX service not found PSM:%d Proto:%d SCN:%d", psm,
   2440         mx_proto_id, mx_chan_id);
   2441     return BTM_NO_RESOURCES;
   2442   }
   2443 
   2444   if ((btm_cb.security_mode == BTM_SEC_MODE_SC) &&
   2445       (!btm_sec_is_serv_level0(psm))) {
   2446     security_required = btm_sec_set_serv_level4_flags(
   2447         p_serv_rec->security_flags, is_originator);
   2448   } else {
   2449     security_required = p_serv_rec->security_flags;
   2450   }
   2451 
   2452   /* there are some devices (moto phone) which connects to several services at
   2453    * the same time */
   2454   /* we will process one after another */
   2455   if ((p_dev_rec->p_callback) ||
   2456       (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)) {
   2457     BTM_TRACE_EVENT("%s() service PSM:%d Proto:%d SCN:%d delayed  state: %s",
   2458                     __func__, psm, mx_proto_id, mx_chan_id,
   2459                     btm_pair_state_descr(btm_cb.pairing_state));
   2460 
   2461     rc = BTM_CMD_STARTED;
   2462 
   2463     if ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED ||
   2464          btm_cb.security_mode == BTM_SEC_MODE_NONE ||
   2465          btm_cb.security_mode == BTM_SEC_MODE_SERVICE ||
   2466          btm_cb.security_mode == BTM_SEC_MODE_LINK) ||
   2467         (BTM_SM4_KNOWN == p_dev_rec->sm4) ||
   2468         (BTM_SEC_IS_SM4(p_dev_rec->sm4) &&
   2469          (btm_sec_is_upgrade_possible(p_dev_rec, is_originator) == false))) {
   2470       /* legacy mode - local is legacy or local is lisbon/peer is legacy
   2471        * or SM4 with no possibility of link key upgrade */
   2472       if (is_originator) {
   2473         if (((security_required & BTM_SEC_OUT_FLAGS) == 0) ||
   2474             ((((security_required & BTM_SEC_OUT_FLAGS) ==
   2475                BTM_SEC_OUT_AUTHENTICATE) &&
   2476               btm_dev_authenticated(p_dev_rec))) ||
   2477             ((((security_required & BTM_SEC_OUT_FLAGS) ==
   2478                (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) &&
   2479               btm_dev_encrypted(p_dev_rec)))) {
   2480           rc = BTM_SUCCESS;
   2481         }
   2482       } else {
   2483         if (((security_required & BTM_SEC_IN_FLAGS) == 0) ||
   2484             ((((security_required & BTM_SEC_IN_FLAGS) ==
   2485                BTM_SEC_IN_AUTHENTICATE) &&
   2486               btm_dev_authenticated(p_dev_rec))) ||
   2487             (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHORIZE) &&
   2488              (btm_dev_authorized(p_dev_rec) ||
   2489               btm_serv_trusted(p_dev_rec, p_serv_rec))) ||
   2490             (((security_required & BTM_SEC_IN_FLAGS) ==
   2491               (BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_AUTHENTICATE)) &&
   2492              ((btm_dev_authorized(p_dev_rec) ||
   2493                btm_serv_trusted(p_dev_rec, p_serv_rec)) &&
   2494               btm_dev_authenticated(p_dev_rec))) ||
   2495             (((security_required & BTM_SEC_IN_FLAGS) ==
   2496               (BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT)) &&
   2497              ((btm_dev_authorized(p_dev_rec) ||
   2498                btm_serv_trusted(p_dev_rec, p_serv_rec)) &&
   2499               btm_dev_encrypted(p_dev_rec))) ||
   2500             ((((security_required & BTM_SEC_IN_FLAGS) ==
   2501                (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) &&
   2502               btm_dev_encrypted(p_dev_rec)))) {
   2503           // Check for 16 digits (or MITM)
   2504           if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) ||
   2505               (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) ==
   2506                 BTM_SEC_IN_MIN_16_DIGIT_PIN) &&
   2507                btm_dev_16_digit_authenticated(p_dev_rec))) {
   2508             rc = BTM_SUCCESS;
   2509           }
   2510         }
   2511       }
   2512       if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) &&
   2513           (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   2514         rc = BTM_CMD_STARTED;
   2515       }
   2516     }
   2517 
   2518     if (rc == BTM_SUCCESS) {
   2519       BTM_TRACE_EVENT("%s: allow to bypass, checking authorization", __func__);
   2520       /* the security in BTM_SEC_IN_FLAGS is fullfilled so far, check the
   2521        * requirements in */
   2522       /* btm_sec_execute_procedure */
   2523       if ((is_originator &&
   2524            (p_serv_rec->security_flags & BTM_SEC_OUT_AUTHORIZE)) ||
   2525           (!is_originator &&
   2526            (p_serv_rec->security_flags & BTM_SEC_IN_AUTHORIZE))) {
   2527         BTM_TRACE_EVENT("%s: still need authorization", __func__);
   2528         rc = BTM_CMD_STARTED;
   2529       }
   2530     }
   2531 
   2532     /* Check whether there is a pending security procedure, if so we should
   2533      * always queue */
   2534     /* the new security request */
   2535     if (p_dev_rec->sec_state != BTM_SEC_STATE_IDLE) {
   2536       BTM_TRACE_EVENT("%s: There is a pending security procedure", __func__);
   2537       rc = BTM_CMD_STARTED;
   2538     }
   2539     if (rc == BTM_CMD_STARTED) {
   2540       BTM_TRACE_EVENT("%s: call btm_sec_queue_mx_request", __func__);
   2541       btm_sec_queue_mx_request(bd_addr, psm, is_originator, mx_proto_id,
   2542                                mx_chan_id, p_callback, p_ref_data);
   2543     } else /* rc == BTM_SUCCESS */
   2544     {
   2545       /* access granted */
   2546       if (p_callback) {
   2547         (*p_callback)(&bd_addr, transport, p_ref_data, (uint8_t)rc);
   2548       }
   2549     }
   2550 
   2551     BTM_TRACE_EVENT("%s: return with rc = 0x%02x in delayed state %s", __func__,
   2552                     rc, btm_pair_state_descr(btm_cb.pairing_state));
   2553     return rc;
   2554   }
   2555 
   2556   if ((!is_originator) && ((security_required & BTM_SEC_MODE4_LEVEL4) ||
   2557                            (btm_cb.security_mode == BTM_SEC_MODE_SC))) {
   2558     bool local_supports_sc =
   2559         controller_get_interface()->supports_secure_connections();
   2560     /* acceptor receives service connection establishment Request for */
   2561     /* Secure Connections Only service */
   2562     if (!(local_supports_sc) ||
   2563         !(p_dev_rec->remote_supports_secure_connections)) {
   2564       BTM_TRACE_DEBUG("%s: SC only service,local_support_for_sc %d,",
   2565                       "remote_support_for_sc %d: fail pairing", __func__,
   2566                       local_supports_sc,
   2567                       p_dev_rec->remote_supports_secure_connections);
   2568 
   2569       if (p_callback)
   2570         (*p_callback)(&bd_addr, transport, (void*)p_ref_data,
   2571                       BTM_MODE4_LEVEL4_NOT_SUPPORTED);
   2572 
   2573       return (BTM_MODE4_LEVEL4_NOT_SUPPORTED);
   2574     }
   2575   }
   2576 
   2577   p_dev_rec->p_cur_service = p_serv_rec;
   2578   p_dev_rec->security_required = security_required;
   2579 
   2580   if (btm_cb.security_mode == BTM_SEC_MODE_SP ||
   2581       btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
   2582       btm_cb.security_mode == BTM_SEC_MODE_SC) {
   2583     if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
   2584       if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) &&
   2585           (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   2586         /* BTM_LKEY_TYPE_AUTH_COMB_P_256 is the only acceptable key in this case
   2587          */
   2588         if ((p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) != 0) {
   2589           p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
   2590         }
   2591 
   2592         p_dev_rec->sec_flags &=
   2593             ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
   2594               BTM_SEC_AUTHENTICATED);
   2595         BTM_TRACE_DEBUG("%s: sec_flags:0x%x", __func__, p_dev_rec->sec_flags);
   2596       } else {
   2597         /* If we already have a link key, check if that link key is good enough
   2598          */
   2599         btm_sec_check_upgrade(p_dev_rec, is_originator);
   2600       }
   2601     }
   2602   }
   2603 
   2604   p_dev_rec->is_originator = is_originator;
   2605   p_dev_rec->p_callback = p_callback;
   2606   p_dev_rec->p_ref_data = p_ref_data;
   2607 
   2608   /* Although authentication and encryption are per connection */
   2609   /* authorization is per access request.  For example when serial connection */
   2610   /* is up and authorized and client requests to read file (access to other */
   2611   /* scn, we need to request user's permission again. */
   2612   p_dev_rec->sec_flags &= ~(BTM_SEC_AUTHORIZED);
   2613 
   2614   BTM_TRACE_EVENT(
   2615       "%s() proto_id:%d chan_id:%d State:%d Flags:0x%x Required:0x%x Service "
   2616       "ID:%d",
   2617       __func__, mx_proto_id, mx_chan_id, p_dev_rec->sec_state,
   2618       p_dev_rec->sec_flags, p_dev_rec->security_required,
   2619       p_dev_rec->p_cur_service->service_id);
   2620 
   2621   rc = btm_sec_execute_procedure(p_dev_rec);
   2622   if (rc != BTM_CMD_STARTED) {
   2623     if (p_callback) {
   2624       p_dev_rec->p_callback = NULL;
   2625       (*p_callback)(&bd_addr, transport, p_ref_data, (uint8_t)rc);
   2626     }
   2627   }
   2628 
   2629   return rc;
   2630 }
   2631 
   2632 /*******************************************************************************
   2633  *
   2634  * Function         btm_sec_conn_req
   2635  *
   2636  * Description      This function is when the peer device is requesting
   2637  *                  connection
   2638  *
   2639  * Returns          void
   2640  *
   2641  ******************************************************************************/
   2642 void btm_sec_conn_req(const RawAddress& bda, uint8_t* dc) {
   2643   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
   2644 
   2645   /* Some device may request a connection before we are done with the HCI_Reset
   2646    * sequence */
   2647   if (!controller_get_interface()->get_is_ready()) {
   2648     BTM_TRACE_EVENT("Security Manager: connect request when device not ready");
   2649     btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE);
   2650     return;
   2651   }
   2652 
   2653   /* Security guys wants us not to allow connection from not paired devices */
   2654 
   2655   /* Check if connection is allowed for only paired devices */
   2656   if (btm_cb.connect_only_paired) {
   2657     if (!p_dev_rec || !(p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED)) {
   2658       BTM_TRACE_EVENT(
   2659           "Security Manager: connect request from non-paired device");
   2660       btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE);
   2661       return;
   2662     }
   2663   }
   2664 
   2665 #if (BTM_ALLOW_CONN_IF_NONDISCOVER == FALSE)
   2666   /* If non-discoverable, only allow known devices to connect */
   2667   if (btm_cb.btm_inq_vars.discoverable_mode == BTM_NON_DISCOVERABLE) {
   2668     if (!p_dev_rec) {
   2669       BTM_TRACE_EVENT(
   2670           "Security Manager: connect request from not paired device");
   2671       btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE);
   2672       return;
   2673     }
   2674   }
   2675 #endif
   2676 
   2677   if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   2678       (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
   2679       (btm_cb.pairing_bda == bda)) {
   2680     BTM_TRACE_EVENT(
   2681         "Security Manager: reject connect request from bonding device");
   2682 
   2683     /* incoming connection from bonding device is rejected */
   2684     btm_cb.pairing_flags |= BTM_PAIR_FLAGS_REJECTED_CONNECT;
   2685     btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE);
   2686     return;
   2687   }
   2688 
   2689   /* Host is not interested or approved connection.  Save BDA and DC and */
   2690   /* pass request to L2CAP */
   2691   btm_cb.connecting_bda = bda;
   2692   memcpy(btm_cb.connecting_dc, dc, DEV_CLASS_LEN);
   2693 
   2694   if (l2c_link_hci_conn_req(bda)) {
   2695     if (!p_dev_rec) {
   2696       /* accept the connection -> allocate a device record */
   2697       p_dev_rec = btm_sec_alloc_dev(bda);
   2698     }
   2699     if (p_dev_rec) {
   2700       p_dev_rec->sm4 |= BTM_SM4_CONN_PEND;
   2701     }
   2702   }
   2703 }
   2704 
   2705 /*******************************************************************************
   2706  *
   2707  * Function         btm_sec_bond_cancel_complete
   2708  *
   2709  * Description      This function is called to report bond cancel complete
   2710  *                  event.
   2711  *
   2712  * Returns          void
   2713  *
   2714  ******************************************************************************/
   2715 static void btm_sec_bond_cancel_complete(void) {
   2716   tBTM_SEC_DEV_REC* p_dev_rec;
   2717 
   2718   if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) ||
   2719       (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_cb.pairing_state &&
   2720        BTM_PAIR_FLAGS_WE_STARTED_DD & btm_cb.pairing_flags) ||
   2721       (btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME &&
   2722        BTM_PAIR_FLAGS_WE_CANCEL_DD & btm_cb.pairing_flags)) {
   2723     /* for dedicated bonding in legacy mode, authentication happens at "link
   2724      * level"
   2725      * btm_sec_connected is called with failed status.
   2726      * In theory, the code that handles is_pairing_device/true should clean out
   2727      * security related code.
   2728      * However, this function may clean out the security related flags and
   2729      * btm_sec_connected would not know
   2730      * this function also needs to do proper clean up.
   2731      */
   2732     p_dev_rec = btm_find_dev(btm_cb.pairing_bda);
   2733     if (p_dev_rec != NULL) p_dev_rec->security_required = BTM_SEC_NONE;
   2734     btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   2735 
   2736     /* Notify application that the cancel succeeded */
   2737     if (btm_cb.api.p_bond_cancel_cmpl_callback)
   2738       btm_cb.api.p_bond_cancel_cmpl_callback(BTM_SUCCESS);
   2739   }
   2740 }
   2741 
   2742 /*******************************************************************************
   2743  *
   2744  * Function         btm_create_conn_cancel_complete
   2745  *
   2746  * Description      This function is called when the command complete message
   2747  *                  is received from the HCI for the create connection cancel
   2748  *                  command.
   2749  *
   2750  * Returns          void
   2751  *
   2752  ******************************************************************************/
   2753 void btm_create_conn_cancel_complete(uint8_t* p) {
   2754   uint8_t status;
   2755 
   2756   STREAM_TO_UINT8(status, p);
   2757   BTM_TRACE_EVENT("btm_create_conn_cancel_complete(): in State: %s  status:%d",
   2758                   btm_pair_state_descr(btm_cb.pairing_state), status);
   2759 
   2760   /* if the create conn cancel cmd was issued by the bond cancel,
   2761   ** the application needs to be notified that bond cancel succeeded
   2762   */
   2763   switch (status) {
   2764     case HCI_SUCCESS:
   2765       btm_sec_bond_cancel_complete();
   2766       break;
   2767     case HCI_ERR_CONNECTION_EXISTS:
   2768     case HCI_ERR_NO_CONNECTION:
   2769     default:
   2770       /* Notify application of the error */
   2771       if (btm_cb.api.p_bond_cancel_cmpl_callback)
   2772         btm_cb.api.p_bond_cancel_cmpl_callback(BTM_ERR_PROCESSING);
   2773       break;
   2774   }
   2775 }
   2776 
   2777 /*******************************************************************************
   2778  *
   2779  * Function         btm_sec_check_pending_reqs
   2780  *
   2781  * Description      This function is called at the end of the security procedure
   2782  *                  to let L2CAP and RFCOMM know to re-submit any pending
   2783  *                  requests
   2784  *
   2785  * Returns          void
   2786  *
   2787  ******************************************************************************/
   2788 void btm_sec_check_pending_reqs(void) {
   2789   if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) {
   2790     /* First, resubmit L2CAP requests */
   2791     if (btm_cb.sec_req_pending) {
   2792       btm_cb.sec_req_pending = false;
   2793       l2cu_resubmit_pending_sec_req(nullptr);
   2794     }
   2795 
   2796     /* Now, re-submit anything in the mux queue */
   2797     fixed_queue_t* bq = btm_cb.sec_pending_q;
   2798 
   2799     btm_cb.sec_pending_q = fixed_queue_new(SIZE_MAX);
   2800 
   2801     tBTM_SEC_QUEUE_ENTRY* p_e;
   2802     while ((p_e = (tBTM_SEC_QUEUE_ENTRY*)fixed_queue_try_dequeue(bq)) != NULL) {
   2803       /* Check that the ACL is still up before starting security procedures */
   2804       if (btm_bda_to_acl(p_e->bd_addr, p_e->transport) != NULL) {
   2805         if (p_e->psm != 0) {
   2806           BTM_TRACE_EVENT(
   2807               "%s PSM:0x%04x Is_Orig:%u mx_proto_id:%u mx_chan_id:%u", __func__,
   2808               p_e->psm, p_e->is_orig, p_e->mx_proto_id, p_e->mx_chan_id);
   2809 
   2810           btm_sec_mx_access_request(p_e->bd_addr, p_e->psm, p_e->is_orig,
   2811                                     p_e->mx_proto_id, p_e->mx_chan_id,
   2812                                     p_e->p_callback, p_e->p_ref_data);
   2813         } else {
   2814           BTM_SetEncryption(p_e->bd_addr, p_e->transport, p_e->p_callback,
   2815                             p_e->p_ref_data, p_e->sec_act);
   2816         }
   2817       }
   2818 
   2819       osi_free(p_e);
   2820     }
   2821     fixed_queue_free(bq, NULL);
   2822   }
   2823 }
   2824 
   2825 /*******************************************************************************
   2826  *
   2827  * Function         btm_sec_init
   2828  *
   2829  * Description      This function is on the SEC startup
   2830  *
   2831  * Returns          void
   2832  *
   2833  ******************************************************************************/
   2834 void btm_sec_init(uint8_t sec_mode) {
   2835   btm_cb.security_mode = sec_mode;
   2836   btm_cb.pairing_bda = RawAddress::kAny;
   2837   btm_cb.max_collision_delay = BTM_SEC_MAX_COLLISION_DELAY;
   2838 }
   2839 
   2840 /*******************************************************************************
   2841  *
   2842  * Function         btm_sec_device_down
   2843  *
   2844  * Description      This function should be called when device is disabled or
   2845  *                  turned off
   2846  *
   2847  * Returns          void
   2848  *
   2849  ******************************************************************************/
   2850 void btm_sec_device_down(void) {
   2851   BTM_TRACE_EVENT("%s() State: %s", __func__,
   2852                   btm_pair_state_descr(btm_cb.pairing_state));
   2853   btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   2854 }
   2855 
   2856 /*******************************************************************************
   2857  *
   2858  * Function         btm_sec_dev_reset
   2859  *
   2860  * Description      This function should be called after device reset
   2861  *
   2862  * Returns          void
   2863  *
   2864  ******************************************************************************/
   2865 void btm_sec_dev_reset(void) {
   2866   if (controller_get_interface()->supports_simple_pairing()) {
   2867     /* set the default IO capabilities */
   2868     btm_cb.devcb.loc_io_caps = BTM_LOCAL_IO_CAPS;
   2869     /* add mx service to use no security */
   2870     BTM_SetSecurityLevel(false, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX,
   2871                          BTM_SEC_NONE, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0);
   2872   } else {
   2873     btm_cb.security_mode = BTM_SEC_MODE_SERVICE;
   2874   }
   2875 
   2876   BTM_TRACE_DEBUG("btm_sec_dev_reset sec mode: %d", btm_cb.security_mode);
   2877 }
   2878 
   2879 /*******************************************************************************
   2880  *
   2881  * Function         btm_sec_abort_access_req
   2882  *
   2883  * Description      This function is called by the L2CAP or RFCOMM to abort
   2884  *                  the pending operation.
   2885  *
   2886  * Parameters:      bd_addr       - Address of the peer device
   2887  *
   2888  * Returns          void
   2889  *
   2890  ******************************************************************************/
   2891 void btm_sec_abort_access_req(const RawAddress& bd_addr) {
   2892   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
   2893 
   2894   if (!p_dev_rec) return;
   2895 
   2896   if ((p_dev_rec->sec_state != BTM_SEC_STATE_AUTHORIZING) &&
   2897       (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING))
   2898     return;
   2899 
   2900   p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
   2901   p_dev_rec->p_callback = NULL;
   2902 }
   2903 
   2904 /*******************************************************************************
   2905  *
   2906  * Function         btm_sec_dd_create_conn
   2907  *
   2908  * Description      This function is called to create the ACL connection for
   2909  *                  the dedicated boding process
   2910  *
   2911  * Returns          void
   2912  *
   2913  ******************************************************************************/
   2914 static tBTM_STATUS btm_sec_dd_create_conn(tBTM_SEC_DEV_REC* p_dev_rec) {
   2915   tL2C_LCB* p_lcb =
   2916       l2cu_find_lcb_by_bd_addr(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR);
   2917   if (p_lcb && (p_lcb->link_state == LST_CONNECTED ||
   2918                 p_lcb->link_state == LST_CONNECTING)) {
   2919     BTM_TRACE_WARNING("%s Connection already exists", __func__);
   2920     btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
   2921     return BTM_CMD_STARTED;
   2922   }
   2923 
   2924   /* Make sure an L2cap link control block is available */
   2925   if (!p_lcb &&
   2926       (p_lcb = l2cu_allocate_lcb(p_dev_rec->bd_addr, true,
   2927                                  BT_TRANSPORT_BR_EDR)) == NULL) {
   2928     LOG(WARNING) << "Security Manager: failed allocate LCB "
   2929                  << p_dev_rec->bd_addr;
   2930 
   2931     return (BTM_NO_RESOURCES);
   2932   }
   2933 
   2934   /* set up the control block to indicated dedicated bonding */
   2935   btm_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE;
   2936 
   2937   if (l2cu_create_conn(p_lcb, BT_TRANSPORT_BR_EDR) == false) {
   2938     LOG(WARNING) << "Security Manager: failed create allocate LCB "
   2939                  << p_dev_rec->bd_addr;
   2940 
   2941     l2cu_release_lcb(p_lcb);
   2942     return (BTM_NO_RESOURCES);
   2943   }
   2944 
   2945   btm_acl_update_busy_level(BTM_BLI_PAGE_EVT);
   2946 
   2947   VLOG(1) << "Security Manager: " << p_dev_rec->bd_addr;
   2948 
   2949   btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
   2950 
   2951   return (BTM_CMD_STARTED);
   2952 }
   2953 
   2954 bool is_state_getting_name(void* data, void* context) {
   2955   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
   2956 
   2957   if (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME) {
   2958     return false;
   2959   }
   2960   return true;
   2961 }
   2962 
   2963 /*******************************************************************************
   2964  *
   2965  * Function         btm_sec_rmt_name_request_complete
   2966  *
   2967  * Description      This function is called when remote name was obtained from
   2968  *                  the peer device
   2969  *
   2970  * Returns          void
   2971  *
   2972  ******************************************************************************/
   2973 void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr,
   2974                                        uint8_t* p_bd_name, uint8_t status) {
   2975   tBTM_SEC_DEV_REC* p_dev_rec;
   2976   int i;
   2977   DEV_CLASS dev_class;
   2978   uint8_t old_sec_state;
   2979 
   2980   BTM_TRACE_EVENT("btm_sec_rmt_name_request_complete");
   2981   if ((!p_bd_addr && !BTM_ACL_IS_CONNECTED(btm_cb.connecting_bda)) ||
   2982       (p_bd_addr && !BTM_ACL_IS_CONNECTED(*p_bd_addr))) {
   2983     btm_acl_resubmit_page();
   2984   }
   2985 
   2986   /* If remote name request failed, p_bd_addr is null and we need to search */
   2987   /* based on state assuming that we are doing 1 at a time */
   2988   if (p_bd_addr)
   2989     p_dev_rec = btm_find_dev(*p_bd_addr);
   2990   else {
   2991     list_node_t* node =
   2992         list_foreach(btm_cb.sec_dev_rec, is_state_getting_name, NULL);
   2993     if (node != NULL) {
   2994       p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
   2995       p_bd_addr = &p_dev_rec->bd_addr;
   2996     } else {
   2997       p_dev_rec = NULL;
   2998     }
   2999   }
   3000 
   3001   /* Commenting out trace due to obf/compilation problems.
   3002    */
   3003   if (!p_bd_name) p_bd_name = (uint8_t*)"";
   3004 
   3005   if (p_dev_rec) {
   3006     BTM_TRACE_EVENT(
   3007         "%s PairState: %s  RemName: %s  status: %d State:%d  p_dev_rec: "
   3008         "0x%08x ",
   3009         __func__, btm_pair_state_descr(btm_cb.pairing_state), p_bd_name, status,
   3010         p_dev_rec->sec_state, p_dev_rec);
   3011   } else {
   3012     BTM_TRACE_EVENT("%s PairState: %s  RemName: %s  status: %d", __func__,
   3013                     btm_pair_state_descr(btm_cb.pairing_state), p_bd_name,
   3014                     status);
   3015   }
   3016 
   3017   if (p_dev_rec) {
   3018     old_sec_state = p_dev_rec->sec_state;
   3019     if (status == HCI_SUCCESS) {
   3020       strlcpy((char*)p_dev_rec->sec_bd_name, (char*)p_bd_name,
   3021               BTM_MAX_REM_BD_NAME_LEN);
   3022       p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
   3023       BTM_TRACE_EVENT("setting BTM_SEC_NAME_KNOWN sec_flags:0x%x",
   3024                       p_dev_rec->sec_flags);
   3025     } else {
   3026       /* Notify all clients waiting for name to be resolved even if it failed so
   3027        * clients can continue */
   3028       p_dev_rec->sec_bd_name[0] = 0;
   3029     }
   3030 
   3031     if (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME)
   3032       p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
   3033 
   3034     /* Notify all clients waiting for name to be resolved */
   3035     for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) {
   3036       if (btm_cb.p_rmt_name_callback[i] && p_bd_addr)
   3037         (*btm_cb.p_rmt_name_callback[i])(*p_bd_addr, p_dev_rec->dev_class,
   3038                                          p_dev_rec->sec_bd_name);
   3039     }
   3040   } else {
   3041     dev_class[0] = 0;
   3042     dev_class[1] = 0;
   3043     dev_class[2] = 0;
   3044 
   3045     /* Notify all clients waiting for name to be resolved even if not found so
   3046      * clients can continue */
   3047     for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) {
   3048       if (btm_cb.p_rmt_name_callback[i] && p_bd_addr)
   3049         (*btm_cb.p_rmt_name_callback[i])(*p_bd_addr, dev_class, (uint8_t*)"");
   3050     }
   3051 
   3052     return;
   3053   }
   3054 
   3055   /* If we were delaying asking UI for a PIN because name was not resolved, ask
   3056    * now */
   3057   if ((btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_LOCAL_PIN) && p_bd_addr &&
   3058       (btm_cb.pairing_bda == *p_bd_addr)) {
   3059     BTM_TRACE_EVENT(
   3060         "%s() delayed pin now being requested flags:0x%x, "
   3061         "(p_pin_callback=0x%p)",
   3062         __func__, btm_cb.pairing_flags, btm_cb.api.p_pin_callback);
   3063 
   3064     if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0 &&
   3065         btm_cb.api.p_pin_callback) {
   3066       BTM_TRACE_EVENT("%s() calling pin_callback", __func__);
   3067       btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
   3068       (*btm_cb.api.p_pin_callback)(
   3069           p_dev_rec->bd_addr, p_dev_rec->dev_class, p_bd_name,
   3070           (p_dev_rec->p_cur_service == NULL)
   3071               ? false
   3072               : (p_dev_rec->p_cur_service->security_flags &
   3073                  BTM_SEC_IN_MIN_16_DIGIT_PIN));
   3074     }
   3075 
   3076     /* Set the same state again to force the timer to be restarted */
   3077     btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN);
   3078     return;
   3079   }
   3080 
   3081   /* Check if we were delaying bonding because name was not resolved */
   3082   if (btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) {
   3083     if (p_bd_addr && btm_cb.pairing_bda == *p_bd_addr) {
   3084       BTM_TRACE_EVENT("%s() continue bonding sm4: 0x%04x, status:0x%x",
   3085                       __func__, p_dev_rec->sm4, status);
   3086       if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_CANCEL_DD) {
   3087         btm_sec_bond_cancel_complete();
   3088         return;
   3089       }
   3090 
   3091       if (status != HCI_SUCCESS) {
   3092         btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   3093 
   3094         if (btm_cb.api.p_auth_complete_callback)
   3095           (*btm_cb.api.p_auth_complete_callback)(
   3096               p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   3097               status);
   3098         return;
   3099       }
   3100 
   3101       /* if peer is very old legacy devices, HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is
   3102        * not reported */
   3103       if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
   3104         /* set the KNOWN flag only if BTM_PAIR_FLAGS_REJECTED_CONNECT is not
   3105          * set.*/
   3106         /* If it is set, there may be a race condition */
   3107         BTM_TRACE_DEBUG("%s IS_SM4_UNKNOWN Flags:0x%04x", __func__,
   3108                         btm_cb.pairing_flags);
   3109         if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0)
   3110           p_dev_rec->sm4 |= BTM_SM4_KNOWN;
   3111       }
   3112 
   3113       BTM_TRACE_DEBUG("%s, SM4 Value: %x, Legacy:%d,IS SM4:%d, Unknown:%d",
   3114                       __func__, p_dev_rec->sm4,
   3115                       BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4),
   3116                       BTM_SEC_IS_SM4(p_dev_rec->sm4),
   3117                       BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4));
   3118 
   3119       /* BT 2.1 or carkit, bring up the connection to force the peer to request
   3120        *PIN.
   3121        ** Else prefetch (btm_sec_check_prefetch_pin will do the prefetching if
   3122        *needed)
   3123        */
   3124       if ((p_dev_rec->sm4 != BTM_SM4_KNOWN) ||
   3125           !btm_sec_check_prefetch_pin(p_dev_rec)) {
   3126         /* if we rejected incoming connection request, we have to wait
   3127          * HCI_Connection_Complete event */
   3128         /*  before originating  */
   3129         if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) {
   3130           BTM_TRACE_WARNING(
   3131               "%s: waiting HCI_Connection_Complete after rejecting connection",
   3132               __func__);
   3133         }
   3134         /* Both we and the peer are 2.1 - continue to create connection */
   3135         else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) {
   3136           BTM_TRACE_WARNING("%s: failed to start connection", __func__);
   3137 
   3138           btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   3139 
   3140           if (btm_cb.api.p_auth_complete_callback) {
   3141             (*btm_cb.api.p_auth_complete_callback)(
   3142                 p_dev_rec->bd_addr, p_dev_rec->dev_class,
   3143                 p_dev_rec->sec_bd_name, HCI_ERR_MEMORY_FULL);
   3144           }
   3145         }
   3146       }
   3147       return;
   3148     } else {
   3149       BTM_TRACE_WARNING("%s: wrong BDA, retry with pairing BDA", __func__);
   3150       if (BTM_ReadRemoteDeviceName(btm_cb.pairing_bda, NULL,
   3151                                    BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) {
   3152         BTM_TRACE_ERROR("%s: failed to start remote name request", __func__);
   3153         if (btm_cb.api.p_auth_complete_callback) {
   3154           (*btm_cb.api.p_auth_complete_callback)(
   3155               p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   3156               HCI_ERR_MEMORY_FULL);
   3157         }
   3158       };
   3159       return;
   3160     }
   3161   }
   3162 
   3163   /* check if we were delaying link_key_callback because name was not resolved
   3164    */
   3165   if (p_dev_rec->link_key_not_sent) {
   3166     /* If HCI connection complete has not arrived, wait for it */
   3167     if (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) return;
   3168 
   3169     p_dev_rec->link_key_not_sent = false;
   3170     btm_send_link_key_notif(p_dev_rec);
   3171 
   3172     /* If its not us who perform authentication, we should tell stackserver */
   3173     /* that some authentication has been completed                          */
   3174     /* This is required when different entities receive link notification and
   3175      * auth complete */
   3176     if (!(p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE)) {
   3177       if (btm_cb.api.p_auth_complete_callback)
   3178         (*btm_cb.api.p_auth_complete_callback)(
   3179             p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   3180             HCI_SUCCESS);
   3181     }
   3182   }
   3183 
   3184   /* If this is a bonding procedure can disconnect the link now */
   3185   if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
   3186       (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) {
   3187     BTM_TRACE_WARNING("btm_sec_rmt_name_request_complete (none/ce)");
   3188     p_dev_rec->security_required &= ~(BTM_SEC_OUT_AUTHENTICATE);
   3189     l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
   3190     return;
   3191   }
   3192 
   3193   if (old_sec_state != BTM_SEC_STATE_GETTING_NAME) return;
   3194 
   3195   /* If get name failed, notify the waiting layer */
   3196   if (status != HCI_SUCCESS) {
   3197     btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false);
   3198     return;
   3199   }
   3200 
   3201   if (p_dev_rec->sm4 & BTM_SM4_REQ_PEND) {
   3202     BTM_TRACE_EVENT("waiting for remote features!!");
   3203     return;
   3204   }
   3205 
   3206   /* Remote Name succeeded, execute the next security procedure, if any */
   3207   status = (uint8_t)btm_sec_execute_procedure(p_dev_rec);
   3208 
   3209   /* If result is pending reply from the user or from the device is pending */
   3210   if (status == BTM_CMD_STARTED) return;
   3211 
   3212   /* There is no next procedure or start of procedure failed, notify the waiting
   3213    * layer */
   3214   btm_sec_dev_rec_cback_event(p_dev_rec, status, false);
   3215 }
   3216 
   3217 /*******************************************************************************
   3218  *
   3219  * Function         btm_sec_rmt_host_support_feat_evt
   3220  *
   3221  * Description      This function is called when the
   3222  *                  HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is received
   3223  *
   3224  * Returns          void
   3225  *
   3226  ******************************************************************************/
   3227 void btm_sec_rmt_host_support_feat_evt(uint8_t* p) {
   3228   tBTM_SEC_DEV_REC* p_dev_rec;
   3229   RawAddress bd_addr; /* peer address */
   3230   BD_FEATURES features;
   3231 
   3232   STREAM_TO_BDADDR(bd_addr, p);
   3233   p_dev_rec = btm_find_or_alloc_dev(bd_addr);
   3234 
   3235   BTM_TRACE_EVENT("btm_sec_rmt_host_support_feat_evt  sm4: 0x%x  p[0]: 0x%x",
   3236                   p_dev_rec->sm4, p[0]);
   3237 
   3238   if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
   3239     p_dev_rec->sm4 = BTM_SM4_KNOWN;
   3240     STREAM_TO_ARRAY(features, p, HCI_FEATURE_BYTES_PER_PAGE);
   3241     if (HCI_SSP_HOST_SUPPORTED(features)) {
   3242       p_dev_rec->sm4 = BTM_SM4_TRUE;
   3243     }
   3244     BTM_TRACE_EVENT(
   3245         "btm_sec_rmt_host_support_feat_evt sm4: 0x%x features[0]: 0x%x",
   3246         p_dev_rec->sm4, features[0]);
   3247   }
   3248 }
   3249 
   3250 /*******************************************************************************
   3251  *
   3252  * Function         btm_io_capabilities_req
   3253  *
   3254  * Description      This function is called when LM request for the IO
   3255  *                  capability of the local device and
   3256  *                  if the OOB data is present for the device in the event
   3257  *
   3258  * Returns          void
   3259  *
   3260  ******************************************************************************/
   3261 void btm_io_capabilities_req(const RawAddress& p) {
   3262   tBTM_SP_IO_REQ evt_data;
   3263   uint8_t err_code = 0;
   3264   tBTM_SEC_DEV_REC* p_dev_rec;
   3265   bool is_orig = true;
   3266   uint8_t callback_rc = BTM_SUCCESS;
   3267 
   3268   evt_data.bd_addr = p;
   3269 
   3270   /* setup the default response according to compile options */
   3271   /* assume that the local IO capability does not change
   3272    * loc_io_caps is initialized with the default value */
   3273   evt_data.io_cap = btm_cb.devcb.loc_io_caps;
   3274   evt_data.oob_data = BTM_OOB_NONE;
   3275   evt_data.auth_req = BTM_DEFAULT_AUTH_REQ;
   3276 
   3277   BTM_TRACE_EVENT("%s: State: %s", __func__,
   3278                   btm_pair_state_descr(btm_cb.pairing_state));
   3279 
   3280   p_dev_rec = btm_find_or_alloc_dev(evt_data.bd_addr);
   3281 
   3282   BTM_TRACE_DEBUG("%s:Security mode: %d, Num Read Remote Feat pages: %d",
   3283                   __func__, btm_cb.security_mode, p_dev_rec->num_read_pages);
   3284 
   3285   if ((btm_cb.security_mode == BTM_SEC_MODE_SC) &&
   3286       (p_dev_rec->num_read_pages == 0)) {
   3287     BTM_TRACE_EVENT("%s: Device security mode is SC only.",
   3288                     "To continue need to know remote features.", __func__);
   3289 
   3290     p_dev_rec->remote_features_needed = true;
   3291     return;
   3292   }
   3293 
   3294   p_dev_rec->sm4 |= BTM_SM4_TRUE;
   3295 
   3296   BTM_TRACE_EVENT("%s: State: %s  Flags: 0x%04x  p_cur_service: 0x%08x",
   3297                   __func__, btm_pair_state_descr(btm_cb.pairing_state),
   3298                   btm_cb.pairing_flags, p_dev_rec->p_cur_service);
   3299 
   3300   if (p_dev_rec->p_cur_service) {
   3301     BTM_TRACE_EVENT("%s: cur_service psm: 0x%04x, security_flags: 0x%04x",
   3302                     __func__, p_dev_rec->p_cur_service->psm,
   3303                     p_dev_rec->p_cur_service->security_flags);
   3304   }
   3305 
   3306   switch (btm_cb.pairing_state) {
   3307     /* initiator connecting */
   3308     case BTM_PAIR_STATE_IDLE:
   3309       // TODO: Handle Idle pairing state
   3310       // security_required = p_dev_rec->security_required;
   3311       break;
   3312 
   3313     /* received IO capability response already->acceptor */
   3314     case BTM_PAIR_STATE_INCOMING_SSP:
   3315       is_orig = false;
   3316 
   3317       if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) {
   3318         /* acceptor in dedicated bonding */
   3319         evt_data.auth_req = BTM_DEFAULT_DD_AUTH_REQ;
   3320       }
   3321       break;
   3322 
   3323     /* initiator, at this point it is expected to be dedicated bonding
   3324     initiated by local device */
   3325     case BTM_PAIR_STATE_WAIT_PIN_REQ:
   3326       if (evt_data.bd_addr == btm_cb.pairing_bda) {
   3327         evt_data.auth_req = BTM_DEFAULT_DD_AUTH_REQ;
   3328       } else {
   3329         err_code = HCI_ERR_HOST_BUSY_PAIRING;
   3330       }
   3331       break;
   3332 
   3333     /* any other state is unexpected */
   3334     default:
   3335       err_code = HCI_ERR_HOST_BUSY_PAIRING;
   3336       BTM_TRACE_ERROR("%s: Unexpected Pairing state received %d", __func__,
   3337                       btm_cb.pairing_state);
   3338       break;
   3339   }
   3340 
   3341   if (btm_cb.pairing_disabled) {
   3342     /* pairing is not allowed */
   3343     BTM_TRACE_DEBUG("%s: Pairing is not allowed -> fail pairing.", __func__);
   3344     err_code = HCI_ERR_PAIRING_NOT_ALLOWED;
   3345   } else if (btm_cb.security_mode == BTM_SEC_MODE_SC) {
   3346     bool local_supports_sc =
   3347         controller_get_interface()->supports_secure_connections();
   3348     /* device in Secure Connections Only mode */
   3349     if (!(local_supports_sc) ||
   3350         !(p_dev_rec->remote_supports_secure_connections)) {
   3351       BTM_TRACE_DEBUG("%s: SC only service, local_support_for_sc %d,",
   3352                       " remote_support_for_sc 0x%02x -> fail pairing", __func__,
   3353                       local_supports_sc,
   3354                       p_dev_rec->remote_supports_secure_connections);
   3355 
   3356       err_code = HCI_ERR_PAIRING_NOT_ALLOWED;
   3357     }
   3358   }
   3359 
   3360   if (err_code != 0) {
   3361     btsnd_hcic_io_cap_req_neg_reply(evt_data.bd_addr, err_code);
   3362     return;
   3363   }
   3364 
   3365   evt_data.is_orig = is_orig;
   3366 
   3367   if (is_orig) {
   3368     /* local device initiated the pairing non-bonding -> use p_cur_service */
   3369     if (!(btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
   3370         p_dev_rec->p_cur_service &&
   3371         (p_dev_rec->p_cur_service->security_flags & BTM_SEC_OUT_AUTHENTICATE)) {
   3372       if (btm_cb.security_mode == BTM_SEC_MODE_SC) {
   3373         /* SC only mode device requires MITM protection */
   3374         evt_data.auth_req = BTM_AUTH_SP_YES;
   3375       } else {
   3376         evt_data.auth_req =
   3377             (p_dev_rec->p_cur_service->security_flags & BTM_SEC_OUT_MITM)
   3378                 ? BTM_AUTH_SP_YES
   3379                 : BTM_AUTH_SP_NO;
   3380       }
   3381     }
   3382   }
   3383 
   3384   /* Notify L2CAP to increase timeout */
   3385   l2c_pin_code_request(evt_data.bd_addr);
   3386 
   3387   btm_cb.pairing_bda = evt_data.bd_addr;
   3388 
   3389   if (evt_data.bd_addr == btm_cb.connecting_bda)
   3390     memcpy(p_dev_rec->dev_class, btm_cb.connecting_dc, DEV_CLASS_LEN);
   3391 
   3392   btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS);
   3393 
   3394   callback_rc = BTM_SUCCESS;
   3395   if (p_dev_rec->sm4 & BTM_SM4_UPGRADE) {
   3396     p_dev_rec->sm4 &= ~BTM_SM4_UPGRADE;
   3397 
   3398     /* link key upgrade: always use SPGB_YES - assuming we want to save the link
   3399      * key */
   3400     evt_data.auth_req = BTM_AUTH_SPGB_YES;
   3401   } else if (btm_cb.api.p_sp_callback) {
   3402     /* the callback function implementation may change the IO capability... */
   3403     callback_rc = (*btm_cb.api.p_sp_callback)(BTM_SP_IO_REQ_EVT,
   3404                                               (tBTM_SP_EVT_DATA*)&evt_data);
   3405   }
   3406 
   3407   if ((callback_rc == BTM_SUCCESS) || (BTM_OOB_UNKNOWN != evt_data.oob_data)) {
   3408     if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) {
   3409       evt_data.auth_req =
   3410           (BTM_AUTH_DD_BOND | (evt_data.auth_req & BTM_AUTH_YN_BIT));
   3411     }
   3412 
   3413     if (btm_cb.security_mode == BTM_SEC_MODE_SC) {
   3414       /* At this moment we know that both sides are SC capable, device in */
   3415       /* SC only mode requires MITM for any service so let's set MITM bit */
   3416       evt_data.auth_req |= BTM_AUTH_YN_BIT;
   3417       BTM_TRACE_DEBUG(
   3418           "%s: for device in \"SC only\" mode set auth_req to 0x%02x", __func__,
   3419           evt_data.auth_req);
   3420     }
   3421 
   3422     /* if the user does not indicate "reply later" by setting the oob_data to
   3423      * unknown */
   3424     /* send the response right now. Save the current IO capability in the
   3425      * control block */
   3426     btm_cb.devcb.loc_auth_req = evt_data.auth_req;
   3427     btm_cb.devcb.loc_io_caps = evt_data.io_cap;
   3428 
   3429     BTM_TRACE_EVENT("%s: State: %s  IO_CAP:%d oob_data:%d auth_req:%d",
   3430                     __func__, btm_pair_state_descr(btm_cb.pairing_state),
   3431                     evt_data.io_cap, evt_data.oob_data, evt_data.auth_req);
   3432 
   3433     btsnd_hcic_io_cap_req_reply(evt_data.bd_addr, evt_data.io_cap,
   3434                                 evt_data.oob_data, evt_data.auth_req);
   3435   }
   3436 }
   3437 
   3438 /*******************************************************************************
   3439  *
   3440  * Function         btm_io_capabilities_rsp
   3441  *
   3442  * Description      This function is called when the IO capability of the
   3443  *                  specified device is received
   3444  *
   3445  * Returns          void
   3446  *
   3447  ******************************************************************************/
   3448 void btm_io_capabilities_rsp(uint8_t* p) {
   3449   tBTM_SEC_DEV_REC* p_dev_rec;
   3450   tBTM_SP_IO_RSP evt_data;
   3451 
   3452   STREAM_TO_BDADDR(evt_data.bd_addr, p);
   3453   STREAM_TO_UINT8(evt_data.io_cap, p);
   3454   STREAM_TO_UINT8(evt_data.oob_data, p);
   3455   STREAM_TO_UINT8(evt_data.auth_req, p);
   3456 
   3457   /* Allocate a new device record or reuse the oldest one */
   3458   p_dev_rec = btm_find_or_alloc_dev(evt_data.bd_addr);
   3459 
   3460   /* If no security is in progress, this indicates incoming security */
   3461   if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) {
   3462     btm_cb.pairing_bda = evt_data.bd_addr;
   3463 
   3464     btm_sec_change_pairing_state(BTM_PAIR_STATE_INCOMING_SSP);
   3465 
   3466     /* Make sure we reset the trusted mask to help against attacks */
   3467     BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask);
   3468 
   3469     /* work around for FW bug */
   3470     btm_inq_stop_on_ssp();
   3471   }
   3472 
   3473   /* Notify L2CAP to increase timeout */
   3474   l2c_pin_code_request(evt_data.bd_addr);
   3475 
   3476   /* We must have a device record here.
   3477    * Use the connecting device's CoD for the connection */
   3478   if (evt_data.bd_addr == btm_cb.connecting_bda)
   3479     memcpy(p_dev_rec->dev_class, btm_cb.connecting_dc, DEV_CLASS_LEN);
   3480 
   3481   /* peer sets dedicated bonding bit and we did not initiate dedicated bonding
   3482    */
   3483   if (btm_cb.pairing_state ==
   3484           BTM_PAIR_STATE_INCOMING_SSP /* peer initiated bonding */
   3485       && (evt_data.auth_req &
   3486           BTM_AUTH_DD_BOND)) /* and dedicated bonding bit is set */
   3487   {
   3488     btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PEER_STARTED_DD;
   3489   }
   3490 
   3491   /* save the IO capability in the device record */
   3492   p_dev_rec->rmt_io_caps = evt_data.io_cap;
   3493   p_dev_rec->rmt_auth_req = evt_data.auth_req;
   3494 
   3495   if (btm_cb.api.p_sp_callback)
   3496     (*btm_cb.api.p_sp_callback)(BTM_SP_IO_RSP_EVT,
   3497                                 (tBTM_SP_EVT_DATA*)&evt_data);
   3498 }
   3499 
   3500 /*******************************************************************************
   3501  *
   3502  * Function         btm_proc_sp_req_evt
   3503  *
   3504  * Description      This function is called to process/report
   3505  *                  HCI_USER_CONFIRMATION_REQUEST_EVT
   3506  *                  or HCI_USER_PASSKEY_REQUEST_EVT
   3507  *                  or HCI_USER_PASSKEY_NOTIFY_EVT
   3508  *
   3509  * Returns          void
   3510  *
   3511  ******************************************************************************/
   3512 void btm_proc_sp_req_evt(tBTM_SP_EVT event, uint8_t* p) {
   3513   tBTM_STATUS status = BTM_ERR_PROCESSING;
   3514   tBTM_SP_EVT_DATA evt_data;
   3515   RawAddress& p_bda = evt_data.cfm_req.bd_addr;
   3516   tBTM_SEC_DEV_REC* p_dev_rec;
   3517 
   3518   /* All events start with bd_addr */
   3519   STREAM_TO_BDADDR(p_bda, p);
   3520 
   3521   VLOG(2) << " BDA: " << p_bda << " event: 0x" << std::hex << +event
   3522           << " State: " << btm_pair_state_descr(btm_cb.pairing_state);
   3523 
   3524   p_dev_rec = btm_find_dev(p_bda);
   3525   if ((p_dev_rec != NULL) && (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   3526       (btm_cb.pairing_bda == p_bda)) {
   3527     evt_data.cfm_req.bd_addr = p_dev_rec->bd_addr;
   3528     memcpy(evt_data.cfm_req.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN);
   3529 
   3530     strlcpy((char*)evt_data.cfm_req.bd_name, (char*)p_dev_rec->sec_bd_name,
   3531             BTM_MAX_REM_BD_NAME_LEN);
   3532 
   3533     switch (event) {
   3534       case BTM_SP_CFM_REQ_EVT:
   3535         /* Numeric confirmation. Need user to conf the passkey */
   3536         btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM);
   3537 
   3538         /* The device record must be allocated in the "IO cap exchange" step */
   3539         STREAM_TO_UINT32(evt_data.cfm_req.num_val, p);
   3540         BTM_TRACE_DEBUG("BTM_SP_CFM_REQ_EVT:  num_val: %u",
   3541                         evt_data.cfm_req.num_val);
   3542 
   3543         evt_data.cfm_req.just_works = true;
   3544 
   3545 /* process user confirm req in association with the auth_req param */
   3546 #if (BTM_LOCAL_IO_CAPS == BTM_IO_CAP_IO)
   3547         if (p_dev_rec->rmt_io_caps == BTM_IO_CAP_UNKNOWN) {
   3548           BTM_TRACE_ERROR(
   3549               "%s did not receive IO cap response prior"
   3550               " to BTM_SP_CFM_REQ_EVT, failing pairing request",
   3551               __func__);
   3552           status = BTM_WRONG_MODE;
   3553           BTM_ConfirmReqReply(status, p_bda);
   3554           return;
   3555         }
   3556         if ((p_dev_rec->rmt_io_caps == BTM_IO_CAP_IO) &&
   3557             (btm_cb.devcb.loc_io_caps == BTM_IO_CAP_IO) &&
   3558             ((p_dev_rec->rmt_auth_req & BTM_AUTH_SP_YES) ||
   3559              (btm_cb.devcb.loc_auth_req & BTM_AUTH_SP_YES))) {
   3560           /* Both devices are DisplayYesNo and one or both devices want to
   3561              authenticate -> use authenticated link key */
   3562           evt_data.cfm_req.just_works = false;
   3563         }
   3564 #endif
   3565         BTM_TRACE_DEBUG(
   3566             "btm_proc_sp_req_evt()  just_works:%d, io loc:%d, rmt:%d, auth "
   3567             "loc:%d, rmt:%d",
   3568             evt_data.cfm_req.just_works, btm_cb.devcb.loc_io_caps,
   3569             p_dev_rec->rmt_io_caps, btm_cb.devcb.loc_auth_req,
   3570             p_dev_rec->rmt_auth_req);
   3571 
   3572         evt_data.cfm_req.loc_auth_req = btm_cb.devcb.loc_auth_req;
   3573         evt_data.cfm_req.rmt_auth_req = p_dev_rec->rmt_auth_req;
   3574         evt_data.cfm_req.loc_io_caps = btm_cb.devcb.loc_io_caps;
   3575         evt_data.cfm_req.rmt_io_caps = p_dev_rec->rmt_io_caps;
   3576         break;
   3577 
   3578       case BTM_SP_KEY_NOTIF_EVT:
   3579         /* Passkey notification (other side is a keyboard) */
   3580         STREAM_TO_UINT32(evt_data.key_notif.passkey, p);
   3581         BTM_TRACE_DEBUG("BTM_SP_KEY_NOTIF_EVT:  passkey: %u",
   3582                         evt_data.key_notif.passkey);
   3583 
   3584         btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
   3585         break;
   3586 
   3587 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
   3588       case BTM_SP_KEY_REQ_EVT:
   3589         /* HCI_USER_PASSKEY_REQUEST_EVT */
   3590         btm_sec_change_pairing_state(BTM_PAIR_STATE_KEY_ENTRY);
   3591         break;
   3592 #endif
   3593     }
   3594 
   3595     if (btm_cb.api.p_sp_callback) {
   3596       status = (*btm_cb.api.p_sp_callback)(event, &evt_data);
   3597       if (status != BTM_NOT_AUTHORIZED) {
   3598         return;
   3599       }
   3600       /* else BTM_NOT_AUTHORIZED means when the app wants to reject the req
   3601        * right now */
   3602     } else if ((event == BTM_SP_CFM_REQ_EVT) &&
   3603                (evt_data.cfm_req.just_works == true)) {
   3604       /* automatically reply with just works if no sp_cback */
   3605       status = BTM_SUCCESS;
   3606     }
   3607 
   3608     if (event == BTM_SP_CFM_REQ_EVT) {
   3609       BTM_TRACE_DEBUG("calling BTM_ConfirmReqReply with status: %d", status);
   3610       BTM_ConfirmReqReply(status, p_bda);
   3611     }
   3612 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
   3613     else if (event == BTM_SP_KEY_REQ_EVT) {
   3614       BTM_PasskeyReqReply(status, p_bda, 0);
   3615     }
   3616 #endif
   3617     return;
   3618   }
   3619 
   3620   /* Something bad. we can only fail this connection */
   3621   btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
   3622 
   3623   if (BTM_SP_CFM_REQ_EVT == event) {
   3624     btsnd_hcic_user_conf_reply(p_bda, false);
   3625   } else if (BTM_SP_KEY_NOTIF_EVT == event) {
   3626     /* do nothing -> it very unlikely to happen.
   3627     This event is most likely to be received by a HID host when it first
   3628     connects to a HID device.
   3629     Usually the Host initiated the connection in this case.
   3630     On Mobile platforms, if there's a security process happening,
   3631     the host probably can not initiate another connection.
   3632     BTW (PC) is another story.  */
   3633     p_dev_rec = btm_find_dev(p_bda);
   3634     if (p_dev_rec != NULL) {
   3635       btm_sec_disconnect(p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE);
   3636     }
   3637   }
   3638 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
   3639   else {
   3640     btsnd_hcic_user_passkey_neg_reply(p_bda);
   3641   }
   3642 #endif
   3643 }
   3644 
   3645 /*******************************************************************************
   3646  *
   3647  * Function         btm_keypress_notif_evt
   3648  *
   3649  * Description      This function is called when a key press notification is
   3650  *                  received
   3651  *
   3652  * Returns          void
   3653  *
   3654  ******************************************************************************/
   3655 void btm_keypress_notif_evt(uint8_t* p) {
   3656   tBTM_SP_KEYPRESS evt_data;
   3657 
   3658   /* parse & report BTM_SP_KEYPRESS_EVT */
   3659   if (btm_cb.api.p_sp_callback) {
   3660     RawAddress& p_bda = evt_data.bd_addr;
   3661 
   3662     STREAM_TO_BDADDR(p_bda, p);
   3663     evt_data.notif_type = *p;
   3664 
   3665     (*btm_cb.api.p_sp_callback)(BTM_SP_KEYPRESS_EVT,
   3666                                 (tBTM_SP_EVT_DATA*)&evt_data);
   3667   }
   3668 }
   3669 
   3670 /*******************************************************************************
   3671  *
   3672  * Function         btm_simple_pair_complete
   3673  *
   3674  * Description      This function is called when simple pairing process is
   3675  *                  complete
   3676  *
   3677  * Returns          void
   3678  *
   3679  ******************************************************************************/
   3680 void btm_simple_pair_complete(uint8_t* p) {
   3681   tBTM_SP_COMPLT evt_data;
   3682   tBTM_SEC_DEV_REC* p_dev_rec;
   3683   uint8_t status;
   3684   bool disc = false;
   3685 
   3686   status = *p++;
   3687   STREAM_TO_BDADDR(evt_data.bd_addr, p);
   3688 
   3689   p_dev_rec = btm_find_dev(evt_data.bd_addr);
   3690   if (p_dev_rec == NULL) {
   3691     LOG(ERROR) << __func__ << " with unknown BDA: " << evt_data.bd_addr;
   3692     return;
   3693   }
   3694 
   3695   BTM_TRACE_EVENT(
   3696       "btm_simple_pair_complete()  Pair State: %s  Status:%d  sec_state: %u",
   3697       btm_pair_state_descr(btm_cb.pairing_state), status, p_dev_rec->sec_state);
   3698 
   3699   evt_data.status = BTM_ERR_PROCESSING;
   3700   if (status == HCI_SUCCESS) {
   3701     evt_data.status = BTM_SUCCESS;
   3702     p_dev_rec->sec_flags |= BTM_SEC_AUTHENTICATED;
   3703   } else {
   3704     if (status == HCI_ERR_PAIRING_NOT_ALLOWED) {
   3705       /* The test spec wants the peer device to get this failure code. */
   3706       btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_DISCONNECT);
   3707 
   3708       /* Change the timer to 1 second */
   3709       alarm_set_on_mloop(btm_cb.pairing_timer, BT_1SEC_TIMEOUT_MS,
   3710                          btm_sec_pairing_timeout, NULL);
   3711     } else if (btm_cb.pairing_bda == evt_data.bd_addr) {
   3712       /* stop the timer */
   3713       alarm_cancel(btm_cb.pairing_timer);
   3714 
   3715       if (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING) {
   3716         /* the initiating side: will receive auth complete event. disconnect ACL
   3717          * at that time */
   3718         disc = true;
   3719       }
   3720     } else
   3721       disc = true;
   3722   }
   3723 
   3724   /* Let the pairing state stay active, p_auth_complete_callback will report the
   3725    * failure */
   3726   evt_data.bd_addr = p_dev_rec->bd_addr;
   3727   memcpy(evt_data.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN);
   3728 
   3729   if (btm_cb.api.p_sp_callback)
   3730     (*btm_cb.api.p_sp_callback)(BTM_SP_COMPLT_EVT,
   3731                                 (tBTM_SP_EVT_DATA*)&evt_data);
   3732 
   3733   if (disc) {
   3734     /* simple pairing failed */
   3735     /* Avoid sending disconnect on HCI_ERR_PEER_USER */
   3736     if ((status != HCI_ERR_PEER_USER) &&
   3737         (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)) {
   3738       btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE,
   3739                                   p_dev_rec->hci_handle);
   3740     }
   3741   }
   3742 }
   3743 
   3744 /*******************************************************************************
   3745  *
   3746  * Function         btm_rem_oob_req
   3747  *
   3748  * Description      This function is called to process/report
   3749  *                  HCI_REMOTE_OOB_DATA_REQUEST_EVT
   3750  *
   3751  * Returns          void
   3752  *
   3753  ******************************************************************************/
   3754 void btm_rem_oob_req(uint8_t* p) {
   3755   tBTM_SP_RMT_OOB evt_data;
   3756   tBTM_SEC_DEV_REC* p_dev_rec;
   3757   BT_OCTET16 c;
   3758   BT_OCTET16 r;
   3759 
   3760   RawAddress& p_bda = evt_data.bd_addr;
   3761 
   3762   STREAM_TO_BDADDR(p_bda, p);
   3763 
   3764   VLOG(2) << __func__ << " BDA: " << p_bda;
   3765   p_dev_rec = btm_find_dev(p_bda);
   3766   if ((p_dev_rec != NULL) && btm_cb.api.p_sp_callback) {
   3767     evt_data.bd_addr = p_dev_rec->bd_addr;
   3768     memcpy(evt_data.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN);
   3769     strlcpy((char*)evt_data.bd_name, (char*)p_dev_rec->sec_bd_name,
   3770             BTM_MAX_REM_BD_NAME_LEN);
   3771 
   3772     btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP);
   3773     if ((*btm_cb.api.p_sp_callback)(BTM_SP_RMT_OOB_EVT,
   3774                                     (tBTM_SP_EVT_DATA*)&evt_data) ==
   3775         BTM_NOT_AUTHORIZED) {
   3776       BTM_RemoteOobDataReply(true, p_bda, c, r);
   3777     }
   3778     return;
   3779   }
   3780 
   3781   /* something bad. we can only fail this connection */
   3782   btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
   3783   btsnd_hcic_rem_oob_neg_reply(p_bda);
   3784 }
   3785 
   3786 /*******************************************************************************
   3787  *
   3788  * Function         btm_read_local_oob_complete
   3789  *
   3790  * Description      This function is called when read local oob data is
   3791  *                  completed by the LM
   3792  *
   3793  * Returns          void
   3794  *
   3795  ******************************************************************************/
   3796 void btm_read_local_oob_complete(uint8_t* p) {
   3797   tBTM_SP_LOC_OOB evt_data;
   3798   uint8_t status = *p++;
   3799 
   3800   BTM_TRACE_EVENT("btm_read_local_oob_complete:%d", status);
   3801   if (status == HCI_SUCCESS) {
   3802     evt_data.status = BTM_SUCCESS;
   3803     STREAM_TO_ARRAY16(evt_data.c, p);
   3804     STREAM_TO_ARRAY16(evt_data.r, p);
   3805   } else
   3806     evt_data.status = BTM_ERR_PROCESSING;
   3807 
   3808   if (btm_cb.api.p_sp_callback) {
   3809     tBTM_SP_EVT_DATA btm_sp_evt_data;
   3810     btm_sp_evt_data.loc_oob = evt_data;
   3811     (*btm_cb.api.p_sp_callback)(BTM_SP_LOC_OOB_EVT, &btm_sp_evt_data);
   3812   }
   3813 }
   3814 
   3815 /*******************************************************************************
   3816  *
   3817  * Function         btm_sec_auth_collision
   3818  *
   3819  * Description      This function is called when authentication or encryption
   3820  *                  needs to be retried at a later time.
   3821  *
   3822  * Returns          void
   3823  *
   3824  ******************************************************************************/
   3825 static void btm_sec_auth_collision(uint16_t handle) {
   3826   tBTM_SEC_DEV_REC* p_dev_rec;
   3827 
   3828   if (!btm_cb.collision_start_time)
   3829     btm_cb.collision_start_time = time_get_os_boottime_ms();
   3830 
   3831   if ((time_get_os_boottime_ms() - btm_cb.collision_start_time) <
   3832       btm_cb.max_collision_delay) {
   3833     if (handle == BTM_SEC_INVALID_HANDLE) {
   3834       p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_AUTHENTICATING);
   3835       if (p_dev_rec == NULL)
   3836         p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_ENCRYPTING);
   3837     } else
   3838       p_dev_rec = btm_find_dev_by_handle(handle);
   3839 
   3840     if (p_dev_rec != NULL) {
   3841       BTM_TRACE_DEBUG(
   3842           "btm_sec_auth_collision: state %d (retrying in a moment...)",
   3843           p_dev_rec->sec_state);
   3844       /* We will restart authentication after timeout */
   3845       if (p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING ||
   3846           p_dev_rec->sec_state == BTM_SEC_STATE_ENCRYPTING)
   3847         p_dev_rec->sec_state = 0;
   3848 
   3849       btm_cb.p_collided_dev_rec = p_dev_rec;
   3850       alarm_set_on_mloop(btm_cb.sec_collision_timer, BT_1SEC_TIMEOUT_MS,
   3851                          btm_sec_collision_timeout, NULL);
   3852     }
   3853   }
   3854 }
   3855 
   3856 /******************************************************************************
   3857  *
   3858  * Function         btm_sec_auth_retry
   3859  *
   3860  * Description      This function is called when authentication or encryption
   3861  *                  needs to be retried at a later time.
   3862  *
   3863  * Returns          TRUE if a security retry required
   3864  *
   3865  *****************************************************************************/
   3866 static bool btm_sec_auth_retry(uint16_t handle, uint8_t status) {
   3867   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
   3868   if (!p_dev_rec) return false;
   3869 
   3870   /* keep the old sm4 flag and clear the retry bit in control block */
   3871   uint8_t old_sm4 = p_dev_rec->sm4;
   3872   p_dev_rec->sm4 &= ~BTM_SM4_RETRY;
   3873 
   3874   if ((btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) &&
   3875       ((old_sm4 & BTM_SM4_RETRY) == 0) && (HCI_ERR_KEY_MISSING == status) &&
   3876       BTM_SEC_IS_SM4(p_dev_rec->sm4)) {
   3877     /* This retry for missing key is for Lisbon or later only.
   3878        Legacy device do not need this. the controller will drive the retry
   3879        automatically
   3880        set the retry bit */
   3881     btm_cb.collision_start_time = 0;
   3882     btm_restore_mode();
   3883     p_dev_rec->sm4 |= BTM_SM4_RETRY;
   3884     p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
   3885     BTM_TRACE_DEBUG("%s Retry for missing key sm4:x%x sec_flags:0x%x", __func__,
   3886                     p_dev_rec->sm4, p_dev_rec->sec_flags);
   3887 
   3888     /* With BRCM controller, we do not need to delete the stored link key in
   3889        controller.
   3890        If the stack may sit on top of other controller, we may need this
   3891        BTM_DeleteStoredLinkKey (bd_addr, NULL); */
   3892     p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
   3893     btm_sec_execute_procedure(p_dev_rec);
   3894     return true;
   3895   }
   3896 
   3897   return false;
   3898 }
   3899 
   3900 /*******************************************************************************
   3901  *
   3902  * Function         btm_sec_auth_complete
   3903  *
   3904  * Description      This function is when authentication of the connection is
   3905  *                  completed by the LM
   3906  *
   3907  * Returns          void
   3908  *
   3909  ******************************************************************************/
   3910 void btm_sec_auth_complete(uint16_t handle, uint8_t status) {
   3911   tBTM_PAIRING_STATE old_state = btm_cb.pairing_state;
   3912   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
   3913   bool are_bonding = false;
   3914 
   3915   if (p_dev_rec) {
   3916     VLOG(2) << __func__ << "Security Manager: in state: "
   3917             << btm_pair_state_descr(btm_cb.pairing_state)
   3918             << " handle:" << handle << " status:" << status
   3919             << "dev->sec_state:" << p_dev_rec->sec_state
   3920             << " bda:" << p_dev_rec->bd_addr
   3921             << "RName:" << p_dev_rec->sec_bd_name;
   3922   } else {
   3923     VLOG(2) << __func__ << "Security Manager: in state: "
   3924             << btm_pair_state_descr(btm_cb.pairing_state)
   3925             << " handle:" << handle << " status:" << status;
   3926   }
   3927 
   3928   /* For transaction collision we need to wait and repeat.  There is no need */
   3929   /* for random timeout because only slave should receive the result */
   3930   if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) ||
   3931       (status == HCI_ERR_DIFF_TRANSACTION_COLLISION)) {
   3932     btm_sec_auth_collision(handle);
   3933     return;
   3934   } else if (btm_sec_auth_retry(handle, status)) {
   3935     return;
   3936   }
   3937 
   3938   btm_cb.collision_start_time = 0;
   3939 
   3940   btm_restore_mode();
   3941 
   3942   /* Check if connection was made just to do bonding.  If we authenticate
   3943      the connection that is up, this is the last event received.
   3944   */
   3945   if (p_dev_rec && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
   3946       !(btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) {
   3947     p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
   3948 
   3949     l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
   3950   }
   3951 
   3952   if (!p_dev_rec) return;
   3953 
   3954   if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   3955       (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
   3956       (p_dev_rec->bd_addr == btm_cb.pairing_bda))
   3957     are_bonding = true;
   3958 
   3959   if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   3960       (p_dev_rec->bd_addr == btm_cb.pairing_bda))
   3961     btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   3962 
   3963   if (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING) {
   3964     if ((btm_cb.api.p_auth_complete_callback && status != HCI_SUCCESS) &&
   3965         (old_state != BTM_PAIR_STATE_IDLE)) {
   3966       (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr,
   3967                                              p_dev_rec->dev_class,
   3968                                              p_dev_rec->sec_bd_name, status);
   3969     }
   3970     return;
   3971   }
   3972 
   3973   /* There can be a race condition, when we are starting authentication and
   3974   ** the peer device is doing encryption.
   3975   ** If first we receive encryption change up, then initiated authentication
   3976   ** can not be performed.  According to the spec we can not do authentication
   3977   ** on the encrypted link, so device is correct.
   3978   */
   3979   if ((status == HCI_ERR_COMMAND_DISALLOWED) &&
   3980       ((p_dev_rec->sec_flags & (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED)) ==
   3981        (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED))) {
   3982     status = HCI_SUCCESS;
   3983   }
   3984   /* Currently we do not notify user if it is a keyboard which connects */
   3985   /* User probably Disabled the keyboard while it was asleap.  Let her try */
   3986   if (btm_cb.api.p_auth_complete_callback) {
   3987     /* report the suthentication status */
   3988     if ((old_state != BTM_PAIR_STATE_IDLE) || (status != HCI_SUCCESS))
   3989       (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr,
   3990                                              p_dev_rec->dev_class,
   3991                                              p_dev_rec->sec_bd_name, status);
   3992   }
   3993 
   3994   p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
   3995 
   3996   /* If this is a bonding procedure can disconnect the link now */
   3997   if (are_bonding) {
   3998     p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
   3999 
   4000     if (status != HCI_SUCCESS) {
   4001       if (((status != HCI_ERR_PEER_USER) &&
   4002            (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)))
   4003         btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_PEER_USER,
   4004                                     p_dev_rec->hci_handle);
   4005     } else {
   4006       BTM_TRACE_DEBUG("TRYING TO DECIDE IF CAN USE SMP_BR_CHNL");
   4007       if (p_dev_rec->new_encryption_key_is_p256 &&
   4008           (btm_sec_use_smp_br_chnl(p_dev_rec))
   4009           /* no LE keys are available, do deriving */
   4010           && (!(p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) ||
   4011               /* or BR key is higher security than existing LE keys */
   4012               (!(p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED) &&
   4013                (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED)))) {
   4014         BTM_TRACE_DEBUG(
   4015             "link encrypted afer dedic bonding can use SMP_BR_CHNL");
   4016 
   4017         if (btm_sec_is_master(p_dev_rec)) {
   4018           // Encryption is required to start SM over BR/EDR
   4019           // indicate that this is encryption after authentication
   4020           BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL,
   4021                             0);
   4022         }
   4023       }
   4024       l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
   4025     }
   4026 
   4027     return;
   4028   }
   4029 
   4030   /* If authentication failed, notify the waiting layer */
   4031   if (status != HCI_SUCCESS) {
   4032     btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false);
   4033 
   4034     if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) {
   4035       btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE,
   4036                                   p_dev_rec->hci_handle);
   4037     }
   4038     return;
   4039   }
   4040 
   4041   p_dev_rec->sec_flags |= BTM_SEC_AUTHENTICATED;
   4042 
   4043   if (p_dev_rec->pin_code_length >= 16 ||
   4044       p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB ||
   4045       p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
   4046     // If we have MITM protection we have a higher level of security than
   4047     // provided by 16 digits PIN
   4048     p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
   4049   }
   4050 
   4051   /* Authentication succeeded, execute the next security procedure, if any */
   4052   status = btm_sec_execute_procedure(p_dev_rec);
   4053 
   4054   /* If there is no next procedure, or procedure failed to start, notify the
   4055    * caller */
   4056   if (status != BTM_CMD_STARTED)
   4057     btm_sec_dev_rec_cback_event(p_dev_rec, status, false);
   4058 }
   4059 
   4060 /*******************************************************************************
   4061  *
   4062  * Function         btm_sec_encrypt_change
   4063  *
   4064  * Description      This function is when encryption of the connection is
   4065  *                  completed by the LM
   4066  *
   4067  * Returns          void
   4068  *
   4069  ******************************************************************************/
   4070 void btm_sec_encrypt_change(uint16_t handle, uint8_t status,
   4071                             uint8_t encr_enable) {
   4072   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
   4073   tACL_CONN* p_acl = NULL;
   4074   uint8_t acl_idx = btm_handle_to_acl_index(handle);
   4075   BTM_TRACE_EVENT(
   4076       "Security Manager: encrypt_change status:%d State:%d, encr_enable = %d",
   4077       status, (p_dev_rec) ? p_dev_rec->sec_state : 0, encr_enable);
   4078   BTM_TRACE_DEBUG("before update p_dev_rec->sec_flags=0x%x",
   4079                   (p_dev_rec) ? p_dev_rec->sec_flags : 0);
   4080 
   4081   /* For transaction collision we need to wait and repeat.  There is no need */
   4082   /* for random timeout because only slave should receive the result */
   4083   if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) ||
   4084       (status == HCI_ERR_DIFF_TRANSACTION_COLLISION)) {
   4085     btm_sec_auth_collision(handle);
   4086     return;
   4087   }
   4088   btm_cb.collision_start_time = 0;
   4089 
   4090   if (!p_dev_rec) return;
   4091 
   4092   if ((status == HCI_SUCCESS) && encr_enable) {
   4093     if (p_dev_rec->hci_handle == handle) {
   4094       p_dev_rec->sec_flags |= (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED);
   4095       if (p_dev_rec->pin_code_length >= 16 ||
   4096           p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB ||
   4097           p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
   4098         p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
   4099       }
   4100     } else {
   4101       p_dev_rec->sec_flags |= (BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED);
   4102     }
   4103   }
   4104 
   4105   /* It is possible that we decrypted the link to perform role switch */
   4106   /* mark link not to be encrypted, so that when we execute security next time
   4107    * it will kick in again */
   4108   if ((status == HCI_SUCCESS) && !encr_enable) {
   4109     if (p_dev_rec->hci_handle == handle)
   4110       p_dev_rec->sec_flags &= ~BTM_SEC_ENCRYPTED;
   4111     else
   4112       p_dev_rec->sec_flags &= ~BTM_SEC_LE_ENCRYPTED;
   4113   }
   4114 
   4115   BTM_TRACE_DEBUG("after update p_dev_rec->sec_flags=0x%x",
   4116                   p_dev_rec->sec_flags);
   4117 
   4118   if (acl_idx != MAX_L2CAP_LINKS) p_acl = &btm_cb.acl_db[acl_idx];
   4119 
   4120   if (p_acl != NULL)
   4121     btm_sec_check_pending_enc_req(p_dev_rec, p_acl->transport, encr_enable);
   4122 
   4123   if (p_acl && p_acl->transport == BT_TRANSPORT_LE) {
   4124     if (status == HCI_ERR_KEY_MISSING || status == HCI_ERR_AUTH_FAILURE ||
   4125         status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) {
   4126       p_dev_rec->sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN);
   4127       p_dev_rec->ble.key_type = BTM_LE_KEY_NONE;
   4128     }
   4129     btm_ble_link_encrypted(p_dev_rec->ble.pseudo_addr, encr_enable);
   4130     return;
   4131   } else {
   4132     /* BR/EDR connection, update the encryption key size to be 16 as always */
   4133     p_dev_rec->enc_key_size = 16;
   4134   }
   4135 
   4136   BTM_TRACE_DEBUG("in %s new_encr_key_256 is %d", __func__,
   4137                   p_dev_rec->new_encryption_key_is_p256);
   4138 
   4139   if ((status == HCI_SUCCESS) && encr_enable &&
   4140       (p_dev_rec->hci_handle == handle)) {
   4141     /* if BR key is temporary no need for LE LTK derivation */
   4142     bool derive_ltk = true;
   4143     if (p_dev_rec->rmt_auth_req == BTM_AUTH_SP_NO &&
   4144         btm_cb.devcb.loc_auth_req == BTM_AUTH_SP_NO) {
   4145       derive_ltk = false;
   4146       BTM_TRACE_DEBUG("%s: BR key is temporary, skip derivation of LE LTK",
   4147                       __func__);
   4148     }
   4149     if (p_dev_rec->new_encryption_key_is_p256) {
   4150       if (btm_sec_use_smp_br_chnl(p_dev_rec) && btm_sec_is_master(p_dev_rec) &&
   4151           /* if LE key is not known, do deriving */
   4152           (!(p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) ||
   4153            /* or BR key is higher security than existing LE keys */
   4154            (!(p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED) &&
   4155             (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED))) &&
   4156           derive_ltk) {
   4157         /* BR/EDR is encrypted with LK that can be used to derive LE LTK */
   4158         p_dev_rec->new_encryption_key_is_p256 = false;
   4159 
   4160         if (p_dev_rec->no_smp_on_br) {
   4161           BTM_TRACE_DEBUG("%s NO SM over BR/EDR", __func__);
   4162         } else {
   4163           BTM_TRACE_DEBUG("%s start SM over BR/EDR", __func__);
   4164           SMP_BR_PairWith(p_dev_rec->bd_addr);
   4165         }
   4166       }
   4167     } else {
   4168       // BR/EDR is successfully encrypted. Correct LK type if needed
   4169       // (BR/EDR LK derived from LE LTK was used for encryption)
   4170       if ((encr_enable == 1) && /* encryption is ON for SSP */
   4171           /* LK type is for BR/EDR SC */
   4172           (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256 ||
   4173            p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   4174         if (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256)
   4175           p_dev_rec->link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB;
   4176         else /* BTM_LKEY_TYPE_AUTH_COMB_P_256 */
   4177           p_dev_rec->link_key_type = BTM_LKEY_TYPE_AUTH_COMB;
   4178 
   4179         BTM_TRACE_DEBUG("updated link key type to %d",
   4180                         p_dev_rec->link_key_type);
   4181         btm_send_link_key_notif(p_dev_rec);
   4182       }
   4183     }
   4184   }
   4185 
   4186   /* If this encryption was started by peer do not need to do anything */
   4187   if (p_dev_rec->sec_state != BTM_SEC_STATE_ENCRYPTING) {
   4188     if (BTM_SEC_STATE_DELAY_FOR_ENC == p_dev_rec->sec_state) {
   4189       p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
   4190       p_dev_rec->p_callback = NULL;
   4191       l2cu_resubmit_pending_sec_req(&p_dev_rec->bd_addr);
   4192     }
   4193     return;
   4194   }
   4195 
   4196   p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
   4197   /* If encryption setup failed, notify the waiting layer */
   4198   if (status != HCI_SUCCESS) {
   4199     btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false);
   4200     return;
   4201   }
   4202 
   4203   /* Encryption setup succeeded, execute the next security procedure, if any */
   4204   status = (uint8_t)btm_sec_execute_procedure(p_dev_rec);
   4205   /* If there is no next procedure, or procedure failed to start, notify the
   4206    * caller */
   4207   if (status != BTM_CMD_STARTED)
   4208     btm_sec_dev_rec_cback_event(p_dev_rec, status, false);
   4209 }
   4210 
   4211 /*******************************************************************************
   4212  *
   4213  * Function         btm_sec_connect_after_reject_timeout
   4214  *
   4215  * Description      Connection for bonding could not start because of the
   4216  *                  collision. Initiate outgoing connection
   4217  *
   4218  * Returns          Pointer to the TLE struct
   4219  *
   4220  ******************************************************************************/
   4221 static void btm_sec_connect_after_reject_timeout(UNUSED_ATTR void* data) {
   4222   tBTM_SEC_DEV_REC* p_dev_rec = btm_cb.p_collided_dev_rec;
   4223 
   4224   BTM_TRACE_EVENT("%s", __func__);
   4225   btm_cb.p_collided_dev_rec = 0;
   4226 
   4227   if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) {
   4228     BTM_TRACE_WARNING("Security Manager: %s: failed to start connection",
   4229                       __func__);
   4230 
   4231     btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4232 
   4233     if (btm_cb.api.p_auth_complete_callback)
   4234       (*btm_cb.api.p_auth_complete_callback)(
   4235           p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   4236           HCI_ERR_MEMORY_FULL);
   4237   }
   4238 }
   4239 
   4240 /*******************************************************************************
   4241  *
   4242  * Function         btm_sec_connected
   4243  *
   4244  * Description      This function is when a connection to the peer device is
   4245  *                  establsihed
   4246  *
   4247  * Returns          void
   4248  *
   4249  ******************************************************************************/
   4250 void btm_sec_connected(const RawAddress& bda, uint16_t handle, uint8_t status,
   4251                        uint8_t enc_mode) {
   4252   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
   4253   uint8_t res;
   4254   bool is_pairing_device = false;
   4255   tACL_CONN* p_acl_cb;
   4256   uint8_t bit_shift = 0;
   4257 
   4258   btm_acl_resubmit_page();
   4259 
   4260   if (p_dev_rec) {
   4261     VLOG(2) << __func__ << "Security Manager: in state: "
   4262             << btm_pair_state_descr(btm_cb.pairing_state)
   4263             << " handle:" << handle << " status:" << status
   4264             << "enc_mode:" << enc_mode << " bda:" << bda
   4265             << "RName:" << p_dev_rec->sec_bd_name;
   4266   } else {
   4267     VLOG(2) << __func__ << "Security Manager: in state: "
   4268             << btm_pair_state_descr(btm_cb.pairing_state)
   4269             << " handle:" << handle << " status:" << status
   4270             << "enc_mode:" << enc_mode << " bda:" << bda;
   4271   }
   4272 
   4273   if (!p_dev_rec) {
   4274     /* There is no device record for new connection.  Allocate one */
   4275     if (status == HCI_SUCCESS) {
   4276       p_dev_rec = btm_sec_alloc_dev(bda);
   4277     } else {
   4278       /* If the device matches with stored paring address
   4279        * reset the paring state to idle */
   4280       if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   4281           btm_cb.pairing_bda == bda) {
   4282         btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4283       }
   4284 
   4285       /* can not find the device record and the status is error,
   4286        * just ignore it */
   4287       return;
   4288     }
   4289   } else /* Update the timestamp for this device */
   4290   {
   4291     bit_shift = (handle == p_dev_rec->ble_hci_handle) ? 8 : 0;
   4292     p_dev_rec->timestamp = btm_cb.dev_rec_count++;
   4293     if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) {
   4294       /* tell L2CAP it's a bonding connection. */
   4295       if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   4296           (btm_cb.pairing_bda == p_dev_rec->bd_addr) &&
   4297           (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) {
   4298         /* if incoming connection failed while pairing, then try to connect and
   4299          * continue */
   4300         /* Motorola S9 disconnects without asking pin code */
   4301         if ((status != HCI_SUCCESS) &&
   4302             (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ)) {
   4303           BTM_TRACE_WARNING(
   4304               "Security Manager: btm_sec_connected: incoming connection failed "
   4305               "without asking PIN");
   4306 
   4307           p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND;
   4308           if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) {
   4309             /* Start timer with 0 to initiate connection with new LCB */
   4310             /* because L2CAP will delete current LCB with this event  */
   4311             btm_cb.p_collided_dev_rec = p_dev_rec;
   4312             alarm_set_on_mloop(btm_cb.sec_collision_timer, 0,
   4313                                btm_sec_connect_after_reject_timeout, NULL);
   4314           } else {
   4315             btm_sec_change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME);
   4316             if (BTM_ReadRemoteDeviceName(p_dev_rec->bd_addr, NULL,
   4317                                          BT_TRANSPORT_BR_EDR) !=
   4318                 BTM_CMD_STARTED) {
   4319               BTM_TRACE_ERROR("%s cannot read remote name", __func__);
   4320               btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4321             }
   4322           }
   4323 #if (BTM_DISC_DURING_RS == TRUE)
   4324           p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
   4325 #endif
   4326           return;
   4327         } else {
   4328           l2cu_update_lcb_4_bonding(p_dev_rec->bd_addr, true);
   4329         }
   4330       }
   4331       /* always clear the pending flag */
   4332       p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND;
   4333     }
   4334   }
   4335 
   4336   p_dev_rec->device_type |= BT_DEVICE_TYPE_BREDR;
   4337 
   4338 #if (BTM_DISC_DURING_RS == TRUE)
   4339   p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
   4340 #endif
   4341 
   4342   p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
   4343 
   4344   if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   4345       (btm_cb.pairing_bda == bda)) {
   4346     /* if we rejected incoming connection from bonding device */
   4347     if ((status == HCI_ERR_HOST_REJECT_DEVICE) &&
   4348         (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)) {
   4349       BTM_TRACE_WARNING(
   4350           "Security Manager: btm_sec_connected: HCI_Conn_Comp Flags:0x%04x, "
   4351           "sm4: 0x%x",
   4352           btm_cb.pairing_flags, p_dev_rec->sm4);
   4353 
   4354       btm_cb.pairing_flags &= ~BTM_PAIR_FLAGS_REJECTED_CONNECT;
   4355       if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
   4356         /* Try again: RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */
   4357         btm_sec_change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME);
   4358         if (BTM_ReadRemoteDeviceName(bda, NULL, BT_TRANSPORT_BR_EDR) !=
   4359             BTM_CMD_STARTED) {
   4360           BTM_TRACE_ERROR("%s cannot read remote name", __func__);
   4361           btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4362         }
   4363         return;
   4364       }
   4365 
   4366       /* if we already have pin code */
   4367       if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) {
   4368         /* Start timer with 0 to initiate connection with new LCB */
   4369         /* because L2CAP will delete current LCB with this event  */
   4370         btm_cb.p_collided_dev_rec = p_dev_rec;
   4371         alarm_set_on_mloop(btm_cb.sec_collision_timer, 0,
   4372                            btm_sec_connect_after_reject_timeout, NULL);
   4373       }
   4374 
   4375       return;
   4376     }
   4377     /* wait for incoming connection without resetting pairing state */
   4378     else if (status == HCI_ERR_CONNECTION_EXISTS) {
   4379       BTM_TRACE_WARNING(
   4380           "Security Manager: btm_sec_connected: Wait for incoming connection");
   4381       return;
   4382     }
   4383 
   4384     is_pairing_device = true;
   4385   }
   4386 
   4387   /* If connection was made to do bonding restore link security if changed */
   4388   btm_restore_mode();
   4389 
   4390   /* if connection fails during pin request, notify application */
   4391   if (status != HCI_SUCCESS) {
   4392     /* If connection failed because of during pairing, need to tell user */
   4393     if (is_pairing_device) {
   4394       p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
   4395       p_dev_rec->sec_flags &=
   4396           ~((BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED) << bit_shift);
   4397       BTM_TRACE_DEBUG("security_required:%x ", p_dev_rec->security_required);
   4398 
   4399       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4400 
   4401       /* We need to notify host that the key is not known any more */
   4402       if (btm_cb.api.p_auth_complete_callback) {
   4403         (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr,
   4404                                                p_dev_rec->dev_class,
   4405                                                p_dev_rec->sec_bd_name, status);
   4406       }
   4407     }
   4408     /*
   4409         Do not send authentication failure, if following conditions hold good
   4410          1.  BTM Sec Pairing state is idle
   4411          2.  Link key for the remote device is present.
   4412          3.  Remote is SSP capable.
   4413      */
   4414     else if ((p_dev_rec->link_key_type <= BTM_LKEY_TYPE_REMOTE_UNIT) &&
   4415              (((status == HCI_ERR_AUTH_FAILURE) ||
   4416                (status == HCI_ERR_KEY_MISSING) ||
   4417                (status == HCI_ERR_HOST_REJECT_SECURITY) ||
   4418                (status == HCI_ERR_PAIRING_NOT_ALLOWED) ||
   4419                (status == HCI_ERR_UNIT_KEY_USED) ||
   4420                (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) ||
   4421                (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) ||
   4422                (status == HCI_ERR_REPEATED_ATTEMPTS)))) {
   4423       p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
   4424       p_dev_rec->sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN << bit_shift);
   4425 
   4426 #ifdef BRCM_NOT_4_BTE
   4427       /* If we rejected pairing, pass this special result code */
   4428       if (btm_cb.acl_disc_reason == HCI_ERR_HOST_REJECT_SECURITY) {
   4429         status = HCI_ERR_HOST_REJECT_SECURITY;
   4430       }
   4431 #endif
   4432 
   4433       /* We need to notify host that the key is not known any more */
   4434       if (btm_cb.api.p_auth_complete_callback) {
   4435         (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr,
   4436                                                p_dev_rec->dev_class,
   4437                                                p_dev_rec->sec_bd_name, status);
   4438       }
   4439     }
   4440 
   4441     if (status == HCI_ERR_CONNECTION_TOUT ||
   4442         status == HCI_ERR_LMP_RESPONSE_TIMEOUT ||
   4443         status == HCI_ERR_UNSPECIFIED || status == HCI_ERR_PAGE_TIMEOUT)
   4444       btm_sec_dev_rec_cback_event(p_dev_rec, BTM_DEVICE_TIMEOUT, false);
   4445     else
   4446       btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false);
   4447 
   4448     return;
   4449   }
   4450 
   4451   /* If initiated dedicated bonding, return the link key now, and initiate
   4452    * disconnect */
   4453   /* If dedicated bonding, and we now have a link key, we are all done */
   4454   if (is_pairing_device && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)) {
   4455     if (p_dev_rec->link_key_not_sent) {
   4456       p_dev_rec->link_key_not_sent = false;
   4457       btm_send_link_key_notif(p_dev_rec);
   4458     }
   4459 
   4460     p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
   4461 
   4462     /* remember flag before it is initialized */
   4463     if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
   4464       res = true;
   4465     else
   4466       res = false;
   4467 
   4468     if (btm_cb.api.p_auth_complete_callback)
   4469       (*btm_cb.api.p_auth_complete_callback)(
   4470           p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   4471           HCI_SUCCESS);
   4472 
   4473     btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4474 
   4475     if (res) {
   4476       /* Let l2cap start bond timer */
   4477       l2cu_update_lcb_4_bonding(p_dev_rec->bd_addr, true);
   4478     }
   4479 
   4480     return;
   4481   }
   4482 
   4483   p_dev_rec->hci_handle = handle;
   4484 
   4485   /* role may not be correct here, it will be updated by l2cap, but we need to
   4486    */
   4487   /* notify btm_acl that link is up, so starting of rmt name request will not */
   4488   /* set paging flag up */
   4489   p_acl_cb = btm_bda_to_acl(bda, BT_TRANSPORT_BR_EDR);
   4490   if (p_acl_cb) {
   4491 /* whatever is in btm_establish_continue() without reporting the BTM_BL_CONN_EVT
   4492  * event */
   4493 #if (BTM_BYPASS_EXTRA_ACL_SETUP == FALSE)
   4494     /* For now there are a some devices that do not like sending */
   4495     /* commands events and data at the same time. */
   4496     /* Set the packet types to the default allowed by the device */
   4497     btm_set_packet_types(p_acl_cb, btm_cb.btm_acl_pkt_types_supported);
   4498 
   4499     if (btm_cb.btm_def_link_policy)
   4500       BTM_SetLinkPolicy(p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy);
   4501 #endif
   4502   }
   4503   btm_acl_created(bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, handle,
   4504                   HCI_ROLE_SLAVE, BT_TRANSPORT_BR_EDR);
   4505 
   4506   /* Initialize security flags.  We need to do that because some            */
   4507   /* authorization complete could have come after the connection is dropped */
   4508   /* and that would set wrong flag that link has been authorized already    */
   4509   p_dev_rec->sec_flags &= ~((BTM_SEC_AUTHORIZED | BTM_SEC_AUTHENTICATED |
   4510                              BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED)
   4511                             << bit_shift);
   4512 
   4513   if (enc_mode != HCI_ENCRYPT_MODE_DISABLED)
   4514     p_dev_rec->sec_flags |=
   4515         ((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED) << bit_shift);
   4516 
   4517   if (btm_cb.security_mode == BTM_SEC_MODE_LINK)
   4518     p_dev_rec->sec_flags |= (BTM_SEC_AUTHENTICATED << bit_shift);
   4519 
   4520   if (p_dev_rec->pin_code_length >= 16 ||
   4521       p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB ||
   4522       p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
   4523     p_dev_rec->sec_flags |= (BTM_SEC_16_DIGIT_PIN_AUTHED << bit_shift);
   4524   }
   4525 
   4526   p_dev_rec->link_key_changed = false;
   4527 
   4528   /* After connection is established we perform security if we do not know */
   4529   /* the name, or if we are originator because some procedure can have */
   4530   /* been scheduled while connection was down */
   4531   BTM_TRACE_DEBUG("is_originator:%d ", p_dev_rec->is_originator);
   4532   if (!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) ||
   4533       p_dev_rec->is_originator) {
   4534     res = btm_sec_execute_procedure(p_dev_rec);
   4535     if (res != BTM_CMD_STARTED)
   4536       btm_sec_dev_rec_cback_event(p_dev_rec, res, false);
   4537   }
   4538   return;
   4539 }
   4540 
   4541 /*******************************************************************************
   4542  *
   4543  * Function         btm_sec_disconnect
   4544  *
   4545  * Description      This function is called to disconnect HCI link
   4546  *
   4547  * Returns          btm status
   4548  *
   4549  ******************************************************************************/
   4550 tBTM_STATUS btm_sec_disconnect(uint16_t handle, uint8_t reason) {
   4551   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
   4552 
   4553   /* In some weird race condition we may not have a record */
   4554   if (!p_dev_rec) {
   4555     btsnd_hcic_disconnect(handle, reason);
   4556     return (BTM_SUCCESS);
   4557   }
   4558 
   4559   /* If we are in the process of bonding we need to tell client that auth failed
   4560    */
   4561   if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   4562       (btm_cb.pairing_bda == p_dev_rec->bd_addr) &&
   4563       (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) {
   4564     /* we are currently doing bonding.  Link will be disconnected when done */
   4565     btm_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE;
   4566     return (BTM_BUSY);
   4567   }
   4568 
   4569   return (btm_sec_send_hci_disconnect(p_dev_rec, reason, handle));
   4570 }
   4571 
   4572 /*******************************************************************************
   4573  *
   4574  * Function         btm_sec_disconnected
   4575  *
   4576  * Description      This function is when a connection to the peer device is
   4577  *                  dropped
   4578  *
   4579  * Returns          void
   4580  *
   4581  ******************************************************************************/
   4582 void btm_sec_disconnected(uint16_t handle, uint8_t reason) {
   4583   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
   4584   uint8_t old_pairing_flags = btm_cb.pairing_flags;
   4585   int result = HCI_ERR_AUTH_FAILURE;
   4586   tBTM_SEC_CALLBACK* p_callback = NULL;
   4587   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
   4588 
   4589   /* If page was delayed for disc complete, can do it now */
   4590   btm_cb.discing = false;
   4591 
   4592   btm_acl_resubmit_page();
   4593 
   4594   if (!p_dev_rec) return;
   4595 
   4596   transport =
   4597       (handle == p_dev_rec->hci_handle) ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE;
   4598 
   4599   p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
   4600 
   4601 #if (BTM_DISC_DURING_RS == TRUE)
   4602   LOG_INFO(LOG_TAG, "%s clearing pending flag handle:%d reason:%d", __func__,
   4603            handle, reason);
   4604   p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
   4605 #endif
   4606 
   4607   /* clear unused flags */
   4608   p_dev_rec->sm4 &= BTM_SM4_TRUE;
   4609 
   4610   VLOG(2) << __func__ << " bd_addr: " << p_dev_rec->bd_addr
   4611           << " name: " << p_dev_rec->sec_bd_name
   4612           << " state: " << btm_pair_state_descr(btm_cb.pairing_state)
   4613           << " reason: " << reason << " sec_req: " << std::hex
   4614           << p_dev_rec->security_required;
   4615 
   4616   BTM_TRACE_EVENT("%s before update sec_flags=0x%x", __func__,
   4617                   p_dev_rec->sec_flags);
   4618 
   4619   /* If we are in the process of bonding we need to tell client that auth failed
   4620    */
   4621   if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   4622       (btm_cb.pairing_bda == p_dev_rec->bd_addr)) {
   4623     btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4624     p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
   4625     if (btm_cb.api.p_auth_complete_callback) {
   4626       /* If the disconnection reason is REPEATED_ATTEMPTS,
   4627          send this error message to complete callback function
   4628          to display the error message of Repeated attempts.
   4629          All others, send HCI_ERR_AUTH_FAILURE. */
   4630       if (reason == HCI_ERR_REPEATED_ATTEMPTS) {
   4631         result = HCI_ERR_REPEATED_ATTEMPTS;
   4632       } else if (old_pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) {
   4633         result = HCI_ERR_HOST_REJECT_SECURITY;
   4634       }
   4635       (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr,
   4636                                              p_dev_rec->dev_class,
   4637                                              p_dev_rec->sec_bd_name, result);
   4638     }
   4639   }
   4640 
   4641   btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, &p_dev_rec->bd_addr,
   4642                                 HCI_SUCCESS);
   4643   /* see sec_flags processing in btm_acl_removed */
   4644 
   4645   if (transport == BT_TRANSPORT_LE) {
   4646     p_dev_rec->ble_hci_handle = BTM_SEC_INVALID_HANDLE;
   4647     p_dev_rec->sec_flags &= ~(BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED);
   4648     p_dev_rec->enc_key_size = 0;
   4649   } else {
   4650     p_dev_rec->hci_handle = BTM_SEC_INVALID_HANDLE;
   4651     p_dev_rec->sec_flags &=
   4652         ~(BTM_SEC_AUTHORIZED | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED |
   4653           BTM_SEC_ROLE_SWITCHED | BTM_SEC_16_DIGIT_PIN_AUTHED);
   4654 
   4655     // Remove temporary key.
   4656     if (p_dev_rec->bond_type == BOND_TYPE_TEMPORARY)
   4657       p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN);
   4658   }
   4659 
   4660   BTM_TRACE_EVENT("%s after update sec_flags=0x%x", __func__,
   4661                   p_dev_rec->sec_flags);
   4662 
   4663   if (p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH) {
   4664     p_dev_rec->sec_state = (transport == BT_TRANSPORT_LE)
   4665                                ? BTM_SEC_STATE_DISCONNECTING
   4666                                : BTM_SEC_STATE_DISCONNECTING_BLE;
   4667     return;
   4668   }
   4669   p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
   4670   p_dev_rec->security_required = BTM_SEC_NONE;
   4671 
   4672   p_callback = p_dev_rec->p_callback;
   4673 
   4674   /* if security is pending, send callback to clean up the security state */
   4675   if (p_callback) {
   4676     p_dev_rec->p_callback =
   4677         NULL; /* when the peer device time out the authentication before
   4678                  we do, this call back must be reset here */
   4679     (*p_callback)(&p_dev_rec->bd_addr, transport, p_dev_rec->p_ref_data,
   4680                   BTM_ERR_PROCESSING);
   4681   }
   4682 }
   4683 
   4684 /*******************************************************************************
   4685  *
   4686  * Function         btm_sec_link_key_notification
   4687  *
   4688  * Description      This function is called when a new connection link key is
   4689  *                  generated
   4690  *
   4691  * Returns          Pointer to the record or NULL
   4692  *
   4693  ******************************************************************************/
   4694 void btm_sec_link_key_notification(const RawAddress& p_bda, uint8_t* p_link_key,
   4695                                    uint8_t key_type) {
   4696   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(p_bda);
   4697   bool we_are_bonding = false;
   4698   bool ltk_derived_lk = false;
   4699 
   4700   VLOG(2) << __func__ << " BDA: " << p_bda << ", TYPE: " << +key_type;
   4701 
   4702   if ((key_type >= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_COMBINATION) &&
   4703       (key_type <=
   4704        BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   4705     ltk_derived_lk = true;
   4706     key_type -= BTM_LTK_DERIVED_LKEY_OFFSET;
   4707   }
   4708   /* If connection was made to do bonding restore link security if changed */
   4709   btm_restore_mode();
   4710 
   4711   if (key_type != BTM_LKEY_TYPE_CHANGED_COMB)
   4712     p_dev_rec->link_key_type = key_type;
   4713 
   4714   p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_KNOWN;
   4715 
   4716   /*
   4717    * Until this point in time, we do not know if MITM was enabled, hence we
   4718    * add the extended security flag here.
   4719    */
   4720   if (p_dev_rec->pin_code_length >= 16 ||
   4721       p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB ||
   4722       p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
   4723     p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED;
   4724   }
   4725 
   4726   /* BR/EDR connection, update the encryption key size to be 16 as always */
   4727   p_dev_rec->enc_key_size = 16;
   4728   memcpy(p_dev_rec->link_key, p_link_key, LINK_KEY_LEN);
   4729 
   4730   if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
   4731       (btm_cb.pairing_bda == p_bda)) {
   4732     if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
   4733       we_are_bonding = true;
   4734     else
   4735       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4736   }
   4737 
   4738   /* save LTK derived LK no matter what */
   4739   if (ltk_derived_lk) {
   4740     if (btm_cb.api.p_link_key_callback) {
   4741       BTM_TRACE_DEBUG("%s() Save LTK derived LK (key_type = %d)", __func__,
   4742                       p_dev_rec->link_key_type);
   4743       (*btm_cb.api.p_link_key_callback)(p_bda, p_dev_rec->dev_class,
   4744                                         p_dev_rec->sec_bd_name, p_link_key,
   4745                                         p_dev_rec->link_key_type);
   4746     }
   4747   } else {
   4748     if ((p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256) ||
   4749         (p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   4750       p_dev_rec->new_encryption_key_is_p256 = true;
   4751       BTM_TRACE_DEBUG("%s set new_encr_key_256 to %d", __func__,
   4752                       p_dev_rec->new_encryption_key_is_p256);
   4753     }
   4754   }
   4755 
   4756   /* If name is not known at this point delay calling callback until the name is
   4757    */
   4758   /* resolved. Unless it is a HID Device and we really need to send all link
   4759    * keys. */
   4760   if ((!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) &&
   4761        ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) !=
   4762         BTM_COD_MAJOR_PERIPHERAL)) &&
   4763       !ltk_derived_lk) {
   4764     VLOG(2) << __func__ << " Delayed BDA: " << p_bda << " Type:" << +key_type;
   4765 
   4766     p_dev_rec->link_key_not_sent = true;
   4767 
   4768     /* If it is for bonding nothing else will follow, so we need to start name
   4769      * resolution */
   4770     if (we_are_bonding) {
   4771       btsnd_hcic_rmt_name_req(p_bda, HCI_PAGE_SCAN_REP_MODE_R1,
   4772                               HCI_MANDATARY_PAGE_SCAN_MODE, 0);
   4773     }
   4774 
   4775     BTM_TRACE_EVENT("rmt_io_caps:%d, sec_flags:x%x, dev_class[1]:x%02x",
   4776                     p_dev_rec->rmt_io_caps, p_dev_rec->sec_flags,
   4777                     p_dev_rec->dev_class[1])
   4778     return;
   4779   }
   4780 
   4781   /* If its not us who perform authentication, we should tell stackserver */
   4782   /* that some authentication has been completed                          */
   4783   /* This is required when different entities receive link notification and auth
   4784    * complete */
   4785   if (!(p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE)
   4786       /* for derived key, always send authentication callback for BR channel */
   4787       || ltk_derived_lk) {
   4788     if (btm_cb.api.p_auth_complete_callback)
   4789       (*btm_cb.api.p_auth_complete_callback)(
   4790           p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   4791           HCI_SUCCESS);
   4792   }
   4793 
   4794 /* We will save link key only if the user authorized it - BTE report link key in
   4795  * all cases */
   4796 #ifdef BRCM_NONE_BTE
   4797   if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED)
   4798 #endif
   4799   {
   4800     if (btm_cb.api.p_link_key_callback) {
   4801       if (ltk_derived_lk) {
   4802         BTM_TRACE_DEBUG(
   4803             "btm_sec_link_key_notification()  LTK derived LK is saved already"
   4804             " (key_type = %d)",
   4805             p_dev_rec->link_key_type);
   4806       } else {
   4807         (*btm_cb.api.p_link_key_callback)(p_bda, p_dev_rec->dev_class,
   4808                                           p_dev_rec->sec_bd_name, p_link_key,
   4809                                           p_dev_rec->link_key_type);
   4810       }
   4811     }
   4812   }
   4813 }
   4814 
   4815 /*******************************************************************************
   4816  *
   4817  * Function         btm_sec_link_key_request
   4818  *
   4819  * Description      This function is called when controller requests link key
   4820  *
   4821  * Returns          Pointer to the record or NULL
   4822  *
   4823  ******************************************************************************/
   4824 void btm_sec_link_key_request(const RawAddress& bda) {
   4825   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda);
   4826 
   4827   VLOG(2) << __func__ << " bda: " << bda;
   4828 
   4829   if ((btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ) &&
   4830       (btm_cb.collision_start_time != 0) &&
   4831       (btm_cb.p_collided_dev_rec->bd_addr == bda)) {
   4832     BTM_TRACE_EVENT(
   4833         "btm_sec_link_key_request() rejecting link key req "
   4834         "State: %d START_TIMEOUT : %d",
   4835         btm_cb.pairing_state, btm_cb.collision_start_time);
   4836     btsnd_hcic_link_key_neg_reply(bda);
   4837     return;
   4838   }
   4839   if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) {
   4840     btsnd_hcic_link_key_req_reply(bda, p_dev_rec->link_key);
   4841     return;
   4842   }
   4843 
   4844   /* Notify L2CAP to increase timeout */
   4845   l2c_pin_code_request(bda);
   4846 
   4847   /* The link key is not in the database and it is not known to the manager */
   4848   btsnd_hcic_link_key_neg_reply(bda);
   4849 }
   4850 
   4851 /*******************************************************************************
   4852  *
   4853  * Function         btm_sec_pairing_timeout
   4854  *
   4855  * Description      This function is called when host does not provide PIN
   4856  *                  within requested time
   4857  *
   4858  * Returns          Pointer to the TLE struct
   4859  *
   4860  ******************************************************************************/
   4861 static void btm_sec_pairing_timeout(UNUSED_ATTR void* data) {
   4862   tBTM_CB* p_cb = &btm_cb;
   4863   tBTM_SEC_DEV_REC* p_dev_rec;
   4864 #if (BTM_LOCAL_IO_CAPS == BTM_IO_CAP_NONE)
   4865   tBTM_AUTH_REQ auth_req = BTM_AUTH_AP_NO;
   4866 #else
   4867   tBTM_AUTH_REQ auth_req = BTM_AUTH_AP_YES;
   4868 #endif
   4869   uint8_t name[2];
   4870 
   4871   p_dev_rec = btm_find_dev(p_cb->pairing_bda);
   4872 
   4873   BTM_TRACE_EVENT("%s  State: %s   Flags: %u", __func__,
   4874                   btm_pair_state_descr(p_cb->pairing_state),
   4875                   p_cb->pairing_flags);
   4876 
   4877   switch (p_cb->pairing_state) {
   4878     case BTM_PAIR_STATE_WAIT_PIN_REQ:
   4879       btm_sec_bond_cancel_complete();
   4880       break;
   4881 
   4882     case BTM_PAIR_STATE_WAIT_LOCAL_PIN:
   4883       if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PRE_FETCH_PIN) == 0)
   4884         btsnd_hcic_pin_code_neg_reply(p_cb->pairing_bda);
   4885       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4886       /* We need to notify the UI that no longer need the PIN */
   4887       if (btm_cb.api.p_auth_complete_callback) {
   4888         if (p_dev_rec == NULL) {
   4889           name[0] = 0;
   4890           (*btm_cb.api.p_auth_complete_callback)(p_cb->pairing_bda, NULL, name,
   4891                                                  HCI_ERR_CONNECTION_TOUT);
   4892         } else
   4893           (*btm_cb.api.p_auth_complete_callback)(
   4894               p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   4895               HCI_ERR_CONNECTION_TOUT);
   4896       }
   4897       break;
   4898 
   4899     case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM:
   4900       btsnd_hcic_user_conf_reply(p_cb->pairing_bda, false);
   4901       /* btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); */
   4902       break;
   4903 
   4904 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
   4905     case BTM_PAIR_STATE_KEY_ENTRY:
   4906       btsnd_hcic_user_passkey_neg_reply(p_cb->pairing_bda);
   4907       /* btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); */
   4908       break;
   4909 #endif /* !BTM_IO_CAP_NONE */
   4910 
   4911     case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS:
   4912       if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
   4913         auth_req |= BTM_AUTH_DD_BOND;
   4914 
   4915       btsnd_hcic_io_cap_req_reply(p_cb->pairing_bda, btm_cb.devcb.loc_io_caps,
   4916                                   BTM_OOB_NONE, auth_req);
   4917       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4918       break;
   4919 
   4920     case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP:
   4921       btsnd_hcic_rem_oob_neg_reply(p_cb->pairing_bda);
   4922       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4923       break;
   4924 
   4925     case BTM_PAIR_STATE_WAIT_DISCONNECT:
   4926       /* simple pairing failed. Started a 1-sec timer at simple pairing
   4927        * complete.
   4928        * now it's time to tear down the ACL link*/
   4929       if (p_dev_rec == NULL) {
   4930         LOG(ERROR) << __func__
   4931                    << " BTM_PAIR_STATE_WAIT_DISCONNECT unknown BDA: "
   4932                    << p_cb->pairing_bda;
   4933         break;
   4934       }
   4935       btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE,
   4936                                   p_dev_rec->hci_handle);
   4937       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4938       break;
   4939 
   4940     case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE:
   4941     case BTM_PAIR_STATE_GET_REM_NAME:
   4942       /* We need to notify the UI that timeout has happened while waiting for
   4943        * authentication*/
   4944       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4945       if (btm_cb.api.p_auth_complete_callback) {
   4946         if (p_dev_rec == NULL) {
   4947           name[0] = 0;
   4948           (*btm_cb.api.p_auth_complete_callback)(p_cb->pairing_bda, NULL, name,
   4949                                                  HCI_ERR_CONNECTION_TOUT);
   4950         } else
   4951           (*btm_cb.api.p_auth_complete_callback)(
   4952               p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   4953               HCI_ERR_CONNECTION_TOUT);
   4954       }
   4955       break;
   4956 
   4957     default:
   4958       BTM_TRACE_WARNING("%s not processed state: %s", __func__,
   4959                         btm_pair_state_descr(btm_cb.pairing_state));
   4960       btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);
   4961       break;
   4962   }
   4963 }
   4964 
   4965 /*******************************************************************************
   4966  *
   4967  * Function         btm_sec_pin_code_request
   4968  *
   4969  * Description      This function is called when controller requests PIN code
   4970  *
   4971  * Returns          Pointer to the record or NULL
   4972  *
   4973  ******************************************************************************/
   4974 void btm_sec_pin_code_request(const RawAddress& p_bda) {
   4975   tBTM_SEC_DEV_REC* p_dev_rec;
   4976   tBTM_CB* p_cb = &btm_cb;
   4977 
   4978   VLOG(2) << __func__ << " BDA: " << p_bda
   4979           << " state: " << btm_pair_state_descr(btm_cb.pairing_state);
   4980 
   4981   if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) {
   4982     if ((p_bda == btm_cb.pairing_bda) &&
   4983         (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE)) {
   4984       btsnd_hcic_pin_code_neg_reply(p_bda);
   4985       return;
   4986     } else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ) ||
   4987                p_bda != btm_cb.pairing_bda) {
   4988       BTM_TRACE_WARNING("btm_sec_pin_code_request() rejected - state: %s",
   4989                         btm_pair_state_descr(btm_cb.pairing_state));
   4990       btsnd_hcic_pin_code_neg_reply(p_bda);
   4991       return;
   4992     }
   4993   }
   4994 
   4995   p_dev_rec = btm_find_or_alloc_dev(p_bda);
   4996   /* received PIN code request. must be non-sm4 */
   4997   p_dev_rec->sm4 = BTM_SM4_KNOWN;
   4998 
   4999   if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) {
   5000     btm_cb.pairing_bda = p_bda;
   5001 
   5002     btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD;
   5003     /* Make sure we reset the trusted mask to help against attacks */
   5004     BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask);
   5005   }
   5006 
   5007   if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED)) {
   5008     BTM_TRACE_EVENT("btm_sec_pin_code_request fixed pin replying");
   5009     btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
   5010     btsnd_hcic_pin_code_req_reply(p_bda, p_cb->cfg.pin_code_len,
   5011                                   p_cb->cfg.pin_code);
   5012     return;
   5013   }
   5014 
   5015   /* Use the connecting device's CoD for the connection */
   5016   if ((p_bda == p_cb->connecting_bda) &&
   5017       (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] ||
   5018        p_cb->connecting_dc[2]))
   5019     memcpy(p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN);
   5020 
   5021   /* We could have started connection after asking user for the PIN code */
   5022   if (btm_cb.pin_code_len != 0) {
   5023     BTM_TRACE_EVENT("btm_sec_pin_code_request bonding sending reply");
   5024     btsnd_hcic_pin_code_req_reply(p_bda, btm_cb.pin_code_len, p_cb->pin_code);
   5025 
   5026     /* Mark that we forwarded received from the user PIN code */
   5027     btm_cb.pin_code_len = 0;
   5028 
   5029     /* We can change mode back right away, that other connection being
   5030      * established */
   5031     /* is not forced to be secure - found a FW issue, so we can not do this
   5032     btm_restore_mode(); */
   5033 
   5034     btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
   5035   }
   5036 
   5037   /* If pairing disabled OR (no PIN callback and not bonding) */
   5038   /* OR we could not allocate entry in the database reject pairing request */
   5039   else if (
   5040       p_cb->pairing_disabled || (p_cb->api.p_pin_callback == NULL)
   5041 
   5042       /* OR Microsoft keyboard can for some reason try to establish connection
   5043        */
   5044       /*  the only thing we can do here is to shut it up.  Normally we will be
   5045          originator */
   5046       /*  for keyboard bonding */
   5047       || (!p_dev_rec->is_originator &&
   5048           ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) ==
   5049            BTM_COD_MAJOR_PERIPHERAL) &&
   5050           (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD))) {
   5051     BTM_TRACE_WARNING(
   5052         "btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev "
   5053         "Rec:%x!",
   5054         p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec);
   5055 
   5056     btsnd_hcic_pin_code_neg_reply(p_bda);
   5057   }
   5058   /* Notify upper layer of PIN request and start expiration timer */
   5059   else {
   5060     btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN);
   5061     /* Pin code request can not come at the same time as connection request */
   5062     p_cb->connecting_bda = p_bda;
   5063     memcpy(p_cb->connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
   5064 
   5065     /* Check if the name is known */
   5066     /* Even if name is not known we might not be able to get one */
   5067     /* this is the case when we are already getting something from the */
   5068     /* device, so HCI level is flow controlled */
   5069     /* Also cannot send remote name request while paging, i.e. connection is not
   5070      * completed */
   5071     if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) {
   5072       BTM_TRACE_EVENT("btm_sec_pin_code_request going for callback");
   5073 
   5074       btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
   5075       if (p_cb->api.p_pin_callback) {
   5076         (*p_cb->api.p_pin_callback)(
   5077             p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   5078             (p_dev_rec->p_cur_service == NULL)
   5079                 ? false
   5080                 : (p_dev_rec->p_cur_service->security_flags &
   5081                    BTM_SEC_IN_MIN_16_DIGIT_PIN));
   5082       }
   5083     } else {
   5084       BTM_TRACE_EVENT("btm_sec_pin_code_request going for remote name");
   5085 
   5086       /* We received PIN code request for the device with unknown name */
   5087       /* it is not user friendly just to ask for the PIN without name */
   5088       /* try to get name at first */
   5089       btsnd_hcic_rmt_name_req(p_dev_rec->bd_addr, HCI_PAGE_SCAN_REP_MODE_R1,
   5090                               HCI_MANDATARY_PAGE_SCAN_MODE, 0);
   5091     }
   5092   }
   5093 
   5094   return;
   5095 }
   5096 
   5097 /*******************************************************************************
   5098  *
   5099  * Function         btm_sec_update_clock_offset
   5100  *
   5101  * Description      This function is called to update clock offset
   5102  *
   5103  * Returns          void
   5104  *
   5105  ******************************************************************************/
   5106 void btm_sec_update_clock_offset(uint16_t handle, uint16_t clock_offset) {
   5107   tBTM_SEC_DEV_REC* p_dev_rec;
   5108   tBTM_INQ_INFO* p_inq_info;
   5109 
   5110   p_dev_rec = btm_find_dev_by_handle(handle);
   5111   if (p_dev_rec == NULL) return;
   5112 
   5113   p_dev_rec->clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID;
   5114 
   5115   p_inq_info = BTM_InqDbRead(p_dev_rec->bd_addr);
   5116   if (p_inq_info == NULL) return;
   5117 
   5118   p_inq_info->results.clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID;
   5119 }
   5120 
   5121 /******************************************************************
   5122  * S T A T I C     F U N C T I O N S
   5123  ******************************************************************/
   5124 
   5125 /*******************************************************************************
   5126  *
   5127  * Function         btm_sec_execute_procedure
   5128  *
   5129  * Description      This function is called to start required security
   5130  *                  procedure.  There is a case when multiplexing protocol
   5131  *                  calls this function on the originating side, connection to
   5132  *                  the peer will not be established.  This function in this
   5133  *                  case performs only authorization.
   5134  *
   5135  * Returns          BTM_SUCCESS     - permission is granted
   5136  *                  BTM_CMD_STARTED - in process
   5137  *                  BTM_NO_RESOURCES  - permission declined
   5138  *
   5139  ******************************************************************************/
   5140 static tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) {
   5141   BTM_TRACE_EVENT(
   5142       "btm_sec_execute_procedure: Required:0x%x Flags:0x%x State:%d",
   5143       p_dev_rec->security_required, p_dev_rec->sec_flags, p_dev_rec->sec_state);
   5144 
   5145   /* There is a chance that we are getting name.  Wait until done. */
   5146   if (p_dev_rec->sec_state != 0) return (BTM_CMD_STARTED);
   5147 
   5148   /* If any security is required, get the name first */
   5149   if (!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) &&
   5150       (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)) {
   5151     BTM_TRACE_EVENT("Security Manager: Start get name");
   5152     if (!btm_sec_start_get_name(p_dev_rec)) {
   5153       return (BTM_NO_RESOURCES);
   5154     }
   5155     return (BTM_CMD_STARTED);
   5156   }
   5157 
   5158   /* If connection is not authenticated and authentication is required */
   5159   /* start authentication and return PENDING to the caller */
   5160   if ((((!(p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) &&
   5161         ((p_dev_rec->is_originator &&
   5162           (p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE)) ||
   5163          (!p_dev_rec->is_originator &&
   5164           (p_dev_rec->security_required & BTM_SEC_IN_AUTHENTICATE)))) ||
   5165        (!(p_dev_rec->sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED) &&
   5166         (!p_dev_rec->is_originator &&
   5167          (p_dev_rec->security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN)))) &&
   5168       (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)) {
   5169 /*
   5170  * We rely on BTM_SEC_16_DIGIT_PIN_AUTHED being set if MITM is in use,
   5171  * as 16 DIGIT is only needed if MITM is not used. Unfortunately, the
   5172  * BTM_SEC_AUTHENTICATED is used for both MITM and non-MITM
   5173  * authenticated connections, hence we cannot distinguish here.
   5174  */
   5175 
   5176 #if (L2CAP_UCD_INCLUDED == TRUE)
   5177     /* if incoming UCD packet, discard it */
   5178     if (!p_dev_rec->is_originator && (p_dev_rec->is_ucd == true))
   5179       return (BTM_FAILED_ON_SECURITY);
   5180 #endif
   5181 
   5182     BTM_TRACE_EVENT("Security Manager: Start authentication");
   5183 
   5184     /*
   5185      * If we do have a link-key, but we end up here because we need an
   5186      * upgrade, then clear the link-key known and authenticated flag before
   5187      * restarting authentication.
   5188      * WARNING: If the controller has link-key, it is optional and
   5189      * recommended for the controller to send a Link_Key_Request.
   5190      * In case we need an upgrade, the only alternative would be to delete
   5191      * the existing link-key. That could lead to very bad user experience
   5192      * or even IOP issues, if a reconnect causes a new connection that
   5193      * requires an upgrade.
   5194      */
   5195     if ((p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) &&
   5196         (!(p_dev_rec->sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED) &&
   5197          (!p_dev_rec->is_originator &&
   5198           (p_dev_rec->security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN)))) {
   5199       p_dev_rec->sec_flags &=
   5200           ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
   5201             BTM_SEC_AUTHENTICATED);
   5202     }
   5203 
   5204     btm_sec_start_authentication(p_dev_rec);
   5205     return (BTM_CMD_STARTED);
   5206   }
   5207 
   5208   /* If connection is not encrypted and encryption is required */
   5209   /* start encryption and return PENDING to the caller */
   5210   if (!(p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) &&
   5211       ((p_dev_rec->is_originator &&
   5212         (p_dev_rec->security_required & BTM_SEC_OUT_ENCRYPT)) ||
   5213        (!p_dev_rec->is_originator &&
   5214         (p_dev_rec->security_required & BTM_SEC_IN_ENCRYPT))) &&
   5215       (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)) {
   5216 #if (L2CAP_UCD_INCLUDED == TRUE)
   5217     /* if incoming UCD packet, discard it */
   5218     if (!p_dev_rec->is_originator && (p_dev_rec->is_ucd == true))
   5219       return (BTM_FAILED_ON_SECURITY);
   5220 #endif
   5221 
   5222     BTM_TRACE_EVENT("Security Manager: Start encryption");
   5223 
   5224     btm_sec_start_encryption(p_dev_rec);
   5225     return (BTM_CMD_STARTED);
   5226   }
   5227 
   5228   if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) &&
   5229       (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
   5230     BTM_TRACE_EVENT(
   5231         "%s: Security Manager: SC only service, but link key type is 0x%02x -",
   5232         "security failure", __func__, p_dev_rec->link_key_type);
   5233     return (BTM_FAILED_ON_SECURITY);
   5234   }
   5235 
   5236   /* If connection is not authorized and authorization is required */
   5237   /* start authorization and return PENDING to the caller */
   5238   if (!(p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED) &&
   5239       ((p_dev_rec->is_originator &&
   5240         (p_dev_rec->security_required & BTM_SEC_OUT_AUTHORIZE)) ||
   5241        (!p_dev_rec->is_originator &&
   5242         (p_dev_rec->security_required & BTM_SEC_IN_AUTHORIZE)))) {
   5243     BTM_TRACE_EVENT(
   5244         "service id:%d, is trusted:%d", p_dev_rec->p_cur_service->service_id,
   5245         (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
   5246                                     p_dev_rec->p_cur_service->service_id)));
   5247     if ((btm_sec_are_all_trusted(p_dev_rec->trusted_mask) == false) &&
   5248         (p_dev_rec->p_cur_service->service_id < BTM_SEC_MAX_SERVICES) &&
   5249         (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
   5250                                     p_dev_rec->p_cur_service->service_id) ==
   5251          false)) {
   5252       BTM_TRACE_EVENT("Security Manager: Start authorization");
   5253       return (btm_sec_start_authorization(p_dev_rec));
   5254     }
   5255   }
   5256 
   5257   /* All required  security procedures already established */
   5258   p_dev_rec->security_required &=
   5259       ~(BTM_SEC_OUT_AUTHORIZE | BTM_SEC_IN_AUTHORIZE |
   5260         BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_AUTHENTICATE |
   5261         BTM_SEC_OUT_ENCRYPT | BTM_SEC_IN_ENCRYPT | BTM_SEC_FORCE_MASTER |
   5262         BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE);
   5263 
   5264   BTM_TRACE_EVENT("Security Manager: trusted:0x%04x%04x",
   5265                   p_dev_rec->trusted_mask[1], p_dev_rec->trusted_mask[0]);
   5266   BTM_TRACE_EVENT("Security Manager: access granted");
   5267 
   5268   return (BTM_SUCCESS);
   5269 }
   5270 
   5271 /*******************************************************************************
   5272  *
   5273  * Function         btm_sec_start_get_name
   5274  *
   5275  * Description      This function is called to start get name procedure
   5276  *
   5277  * Returns          true if started
   5278  *
   5279  ******************************************************************************/
   5280 static bool btm_sec_start_get_name(tBTM_SEC_DEV_REC* p_dev_rec) {
   5281   uint8_t tempstate = p_dev_rec->sec_state;
   5282 
   5283   p_dev_rec->sec_state = BTM_SEC_STATE_GETTING_NAME;
   5284 
   5285   /* 0 and NULL are as timeout and callback params because they are not used in
   5286    * security get name case */
   5287   if ((btm_initiate_rem_name(p_dev_rec->bd_addr, BTM_RMT_NAME_SEC, 0, NULL)) !=
   5288       BTM_CMD_STARTED) {
   5289     p_dev_rec->sec_state = tempstate;
   5290     return (false);
   5291   }
   5292 
   5293   return (true);
   5294 }
   5295 
   5296 /*******************************************************************************
   5297  *
   5298  * Function         btm_sec_start_authentication
   5299  *
   5300  * Description      This function is called to start authentication
   5301  *
   5302  ******************************************************************************/
   5303 static void btm_sec_start_authentication(tBTM_SEC_DEV_REC* p_dev_rec) {
   5304   p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
   5305   btsnd_hcic_auth_request(p_dev_rec->hci_handle);
   5306 }
   5307 
   5308 /*******************************************************************************
   5309  *
   5310  * Function         btm_sec_start_encryption
   5311  *
   5312  * Description      This function is called to start encryption
   5313  *
   5314  ******************************************************************************/
   5315 static void btm_sec_start_encryption(tBTM_SEC_DEV_REC* p_dev_rec) {
   5316   btsnd_hcic_set_conn_encrypt(p_dev_rec->hci_handle, true);
   5317   p_dev_rec->sec_state = BTM_SEC_STATE_ENCRYPTING;
   5318 }
   5319 
   5320 /*******************************************************************************
   5321  *
   5322  * Function         btm_sec_start_authorization
   5323  *
   5324  * Description      This function is called to start authorization
   5325  *
   5326  * Returns          true if started
   5327  *
   5328  ******************************************************************************/
   5329 static uint8_t btm_sec_start_authorization(tBTM_SEC_DEV_REC* p_dev_rec) {
   5330   uint8_t result;
   5331   uint8_t* p_service_name = NULL;
   5332   uint8_t service_id;
   5333 
   5334   if ((p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) ||
   5335       (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE)) {
   5336     if (!btm_cb.api.p_authorize_callback) return (BTM_MODE_UNSUPPORTED);
   5337 
   5338     if (p_dev_rec->p_cur_service) {
   5339 #if BTM_SEC_SERVICE_NAME_LEN > 0
   5340       if (p_dev_rec->is_originator)
   5341         p_service_name = p_dev_rec->p_cur_service->orig_service_name;
   5342       else
   5343         p_service_name = p_dev_rec->p_cur_service->term_service_name;
   5344 #endif
   5345       service_id = p_dev_rec->p_cur_service->service_id;
   5346     } else
   5347       service_id = 0;
   5348 
   5349     /* Send authorization request if not already sent during this service
   5350      * connection */
   5351     if (p_dev_rec->last_author_service_id == BTM_SEC_NO_LAST_SERVICE_ID ||
   5352         p_dev_rec->last_author_service_id != service_id) {
   5353       p_dev_rec->sec_state = BTM_SEC_STATE_AUTHORIZING;
   5354       result = (*btm_cb.api.p_authorize_callback)(
   5355           p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   5356           p_service_name, service_id, p_dev_rec->is_originator);
   5357     }
   5358 
   5359     else /* Already authorized once for this L2CAP bringup */
   5360     {
   5361       BTM_TRACE_DEBUG(
   5362           "btm_sec_start_authorization: (Ignoring extra Authorization prompt "
   5363           "for service %d)",
   5364           service_id);
   5365       return (BTM_SUCCESS);
   5366     }
   5367 
   5368     if (result == BTM_SUCCESS) {
   5369       p_dev_rec->sec_flags |= BTM_SEC_AUTHORIZED;
   5370 
   5371       /* Save the currently authorized service in case we are asked again by
   5372        * another multiplexer layer */
   5373       if (!p_dev_rec->is_originator)
   5374         p_dev_rec->last_author_service_id = service_id;
   5375 
   5376       p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
   5377     }
   5378     return (result);
   5379   }
   5380   btm_sec_start_get_name(p_dev_rec);
   5381   return (BTM_CMD_STARTED);
   5382 }
   5383 
   5384 /*******************************************************************************
   5385  *
   5386  * Function         btm_sec_are_all_trusted
   5387  *
   5388  * Description      This function is called check if all services are trusted
   5389  *
   5390  * Returns          true if all are trusted, otherwise false
   5391  *
   5392  ******************************************************************************/
   5393 bool btm_sec_are_all_trusted(uint32_t p_mask[]) {
   5394   uint32_t trusted_inx;
   5395   for (trusted_inx = 0; trusted_inx < BTM_SEC_SERVICE_ARRAY_SIZE;
   5396        trusted_inx++) {
   5397     if (p_mask[trusted_inx] != BTM_SEC_TRUST_ALL) return (false);
   5398   }
   5399 
   5400   return (true);
   5401 }
   5402 
   5403 /*******************************************************************************
   5404  *
   5405  * Function         btm_sec_find_first_serv
   5406  *
   5407  * Description      Look for the first record in the service database
   5408  *                  with specified PSM
   5409  *
   5410  * Returns          Pointer to the record or NULL
   5411  *
   5412  ******************************************************************************/
   5413 tBTM_SEC_SERV_REC* btm_sec_find_first_serv(CONNECTION_TYPE conn_type,
   5414                                            uint16_t psm) {
   5415   tBTM_SEC_SERV_REC* p_serv_rec = &btm_cb.sec_serv_rec[0];
   5416   int i;
   5417   bool is_originator;
   5418 
   5419 #if (L2CAP_UCD_INCLUDED == TRUE)
   5420 
   5421   if (conn_type & CONNECTION_TYPE_ORIG_MASK)
   5422     is_originator = true;
   5423   else
   5424     is_originator = false;
   5425 #else
   5426   is_originator = conn_type;
   5427 #endif
   5428 
   5429   if (is_originator && btm_cb.p_out_serv && btm_cb.p_out_serv->psm == psm) {
   5430     /* If this is outgoing connection and the PSM matches p_out_serv,
   5431      * use it as the current service */
   5432     return btm_cb.p_out_serv;
   5433   }
   5434 
   5435   /* otherwise, just find the first record with the specified PSM */
   5436   for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) {
   5437     if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) &&
   5438         (p_serv_rec->psm == psm))
   5439       return (p_serv_rec);
   5440   }
   5441   return (NULL);
   5442 }
   5443 
   5444 /*******************************************************************************
   5445  *
   5446  * Function         btm_sec_find_next_serv
   5447  *
   5448  * Description      Look for the next record in the service database
   5449  *                  with specified PSM
   5450  *
   5451  * Returns          Pointer to the record or NULL
   5452  *
   5453  ******************************************************************************/
   5454 static tBTM_SEC_SERV_REC* btm_sec_find_next_serv(tBTM_SEC_SERV_REC* p_cur) {
   5455   tBTM_SEC_SERV_REC* p_serv_rec = &btm_cb.sec_serv_rec[0];
   5456   int i;
   5457 
   5458   for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) {
   5459     if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) &&
   5460         (p_serv_rec->psm == p_cur->psm)) {
   5461       if (p_cur != p_serv_rec) {
   5462         return (p_serv_rec);
   5463       }
   5464     }
   5465   }
   5466   return (NULL);
   5467 }
   5468 
   5469 /*******************************************************************************
   5470  *
   5471  * Function         btm_sec_find_mx_serv
   5472  *
   5473  * Description      Look for the record in the service database with specified
   5474  *                  PSM and multiplexor channel information
   5475  *
   5476  * Returns          Pointer to the record or NULL
   5477  *
   5478  ******************************************************************************/
   5479 static tBTM_SEC_SERV_REC* btm_sec_find_mx_serv(uint8_t is_originator,
   5480                                                uint16_t psm,
   5481                                                uint32_t mx_proto_id,
   5482                                                uint32_t mx_chan_id) {
   5483   tBTM_SEC_SERV_REC* p_out_serv = btm_cb.p_out_serv;
   5484   tBTM_SEC_SERV_REC* p_serv_rec = &btm_cb.sec_serv_rec[0];
   5485   int i;
   5486 
   5487   BTM_TRACE_DEBUG("%s()", __func__);
   5488   if (is_originator && p_out_serv && p_out_serv->psm == psm &&
   5489       p_out_serv->mx_proto_id == mx_proto_id &&
   5490       p_out_serv->orig_mx_chan_id == mx_chan_id) {
   5491     /* If this is outgoing connection and the parameters match p_out_serv,
   5492      * use it as the current service */
   5493     return btm_cb.p_out_serv;
   5494   }
   5495 
   5496   /* otherwise, the old way */
   5497   for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) {
   5498     if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) &&
   5499         (p_serv_rec->psm == psm) && (p_serv_rec->mx_proto_id == mx_proto_id) &&
   5500         ((is_originator && (p_serv_rec->orig_mx_chan_id == mx_chan_id)) ||
   5501          (!is_originator && (p_serv_rec->term_mx_chan_id == mx_chan_id)))) {
   5502       return (p_serv_rec);
   5503     }
   5504   }
   5505   return (NULL);
   5506 }
   5507 
   5508 /*******************************************************************************
   5509  *
   5510  * Function         btm_sec_collision_timeout
   5511  *
   5512  * Description      Encryption could not start because of the collision
   5513  *                  try to do it again
   5514  *
   5515  * Returns          Pointer to the TLE struct
   5516  *
   5517  ******************************************************************************/
   5518 static void btm_sec_collision_timeout(UNUSED_ATTR void* data) {
   5519   BTM_TRACE_EVENT("%s()", __func__);
   5520 
   5521   tBTM_STATUS status = btm_sec_execute_procedure(btm_cb.p_collided_dev_rec);
   5522 
   5523   /* If result is pending reply from the user or from the device is pending */
   5524   if (status != BTM_CMD_STARTED) {
   5525     /* There is no next procedure or start of procedure failed, notify the
   5526      * waiting layer */
   5527     btm_sec_dev_rec_cback_event(btm_cb.p_collided_dev_rec, status, false);
   5528   }
   5529 }
   5530 
   5531 /*******************************************************************************
   5532  *
   5533  * Function         btm_sec_link_key_request
   5534  *
   5535  * Description      This function is called when controller requests link key
   5536  *
   5537  * Returns          Pointer to the record or NULL
   5538  *
   5539  ******************************************************************************/
   5540 static void btm_send_link_key_notif(tBTM_SEC_DEV_REC* p_dev_rec) {
   5541   if (btm_cb.api.p_link_key_callback)
   5542     (*btm_cb.api.p_link_key_callback)(
   5543         p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   5544         p_dev_rec->link_key, p_dev_rec->link_key_type);
   5545 }
   5546 
   5547 /*******************************************************************************
   5548  *
   5549  * Function         BTM_ReadTrustedMask
   5550  *
   5551  * Description      Get trusted mask for the peer device
   5552  *
   5553  * Parameters:      bd_addr   - Address of the device
   5554  *
   5555  * Returns          NULL, if the device record is not found.
   5556  *                  otherwise, the trusted mask
   5557  *
   5558  ******************************************************************************/
   5559 uint32_t* BTM_ReadTrustedMask(const RawAddress& bd_addr) {
   5560   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
   5561   if (p_dev_rec != NULL) return (p_dev_rec->trusted_mask);
   5562   return NULL;
   5563 }
   5564 
   5565 /*******************************************************************************
   5566  *
   5567  * Function         btm_restore_mode
   5568  *
   5569  * Description      This function returns the security mode to previous setting
   5570  *                  if it was changed during bonding.
   5571  *
   5572  *
   5573  * Parameters:      void
   5574  *
   5575  ******************************************************************************/
   5576 static void btm_restore_mode(void) {
   5577   if (btm_cb.security_mode_changed) {
   5578     btm_cb.security_mode_changed = false;
   5579     BTM_TRACE_DEBUG("%s() Auth enable -> %d", __func__,
   5580                     (btm_cb.security_mode == BTM_SEC_MODE_LINK));
   5581     btsnd_hcic_write_auth_enable(
   5582         (uint8_t)(btm_cb.security_mode == BTM_SEC_MODE_LINK));
   5583   }
   5584 
   5585   if (btm_cb.pin_type_changed) {
   5586     btm_cb.pin_type_changed = false;
   5587     btsnd_hcic_write_pin_type(btm_cb.cfg.pin_type);
   5588   }
   5589 }
   5590 
   5591 bool is_sec_state_equal(void* data, void* context) {
   5592   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
   5593   uint8_t* state = static_cast<uint8_t*>(context);
   5594 
   5595   if (p_dev_rec->sec_state == *state) return false;
   5596 
   5597   return true;
   5598 }
   5599 
   5600 /*******************************************************************************
   5601  *
   5602  * Function         btm_sec_find_dev_by_sec_state
   5603  *
   5604  * Description      Look for the record in the device database for the device
   5605  *                  which is being authenticated or encrypted
   5606  *
   5607  * Returns          Pointer to the record or NULL
   5608  *
   5609  ******************************************************************************/
   5610 tBTM_SEC_DEV_REC* btm_sec_find_dev_by_sec_state(uint8_t state) {
   5611   list_node_t* n = list_foreach(btm_cb.sec_dev_rec, is_sec_state_equal, &state);
   5612   if (n) return static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
   5613 
   5614   return NULL;
   5615 }
   5616 
   5617 /*******************************************************************************
   5618  *
   5619  * Function         btm_sec_change_pairing_state
   5620  *
   5621  * Description      This function is called to change pairing state
   5622  *
   5623  ******************************************************************************/
   5624 static void btm_sec_change_pairing_state(tBTM_PAIRING_STATE new_state) {
   5625   tBTM_PAIRING_STATE old_state = btm_cb.pairing_state;
   5626 
   5627   BTM_TRACE_EVENT("%s()  Old: %s", __func__,
   5628                   btm_pair_state_descr(btm_cb.pairing_state));
   5629   BTM_TRACE_EVENT("%s()  New: %s pairing_flags:0x%x", __func__,
   5630                   btm_pair_state_descr(new_state), btm_cb.pairing_flags);
   5631 
   5632   btm_cb.pairing_state = new_state;
   5633 
   5634   if (new_state == BTM_PAIR_STATE_IDLE) {
   5635     alarm_cancel(btm_cb.pairing_timer);
   5636 
   5637     btm_cb.pairing_flags = 0;
   5638     btm_cb.pin_code_len = 0;
   5639 
   5640     /* Make sure the the lcb shows we are not bonding */
   5641     l2cu_update_lcb_4_bonding(btm_cb.pairing_bda, false);
   5642 
   5643     btm_restore_mode();
   5644     btm_sec_check_pending_reqs();
   5645     btm_inq_clear_ssp();
   5646 
   5647     btm_cb.pairing_bda = RawAddress::kAny;
   5648   } else {
   5649     /* If transitioning out of idle, mark the lcb as bonding */
   5650     if (old_state == BTM_PAIR_STATE_IDLE)
   5651       l2cu_update_lcb_4_bonding(btm_cb.pairing_bda, true);
   5652 
   5653     alarm_set_on_mloop(btm_cb.pairing_timer, BTM_SEC_TIMEOUT_VALUE * 1000,
   5654                        btm_sec_pairing_timeout, NULL);
   5655   }
   5656 }
   5657 
   5658 /*******************************************************************************
   5659  *
   5660  * Function         btm_pair_state_descr
   5661  *
   5662  * Description      Return state description for tracing
   5663  *
   5664  ******************************************************************************/
   5665 static const char* btm_pair_state_descr(tBTM_PAIRING_STATE state) {
   5666   switch (state) {
   5667     case BTM_PAIR_STATE_IDLE:
   5668       return ("IDLE");
   5669     case BTM_PAIR_STATE_GET_REM_NAME:
   5670       return ("GET_REM_NAME");
   5671     case BTM_PAIR_STATE_WAIT_PIN_REQ:
   5672       return ("WAIT_PIN_REQ");
   5673     case BTM_PAIR_STATE_WAIT_LOCAL_PIN:
   5674       return ("WAIT_LOCAL_PIN");
   5675     case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM:
   5676       return ("WAIT_NUM_CONFIRM");
   5677     case BTM_PAIR_STATE_KEY_ENTRY:
   5678       return ("KEY_ENTRY");
   5679     case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP:
   5680       return ("WAIT_LOCAL_OOB_RSP");
   5681     case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS:
   5682       return ("WAIT_LOCAL_IOCAPS");
   5683     case BTM_PAIR_STATE_INCOMING_SSP:
   5684       return ("INCOMING_SSP");
   5685     case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE:
   5686       return ("WAIT_AUTH_COMPLETE");
   5687     case BTM_PAIR_STATE_WAIT_DISCONNECT:
   5688       return ("WAIT_DISCONNECT");
   5689   }
   5690 
   5691   return ("???");
   5692 }
   5693 
   5694 /*******************************************************************************
   5695  *
   5696  * Function         btm_sec_dev_rec_cback_event
   5697  *
   5698  * Description      This function calls the callback function with the given
   5699  *                  result and clear the callback function.
   5700  *
   5701  * Parameters:      void
   5702  *
   5703  ******************************************************************************/
   5704 void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec, uint8_t res,
   5705                                  bool is_le_transport) {
   5706   tBTM_SEC_CALLBACK* p_callback = p_dev_rec->p_callback;
   5707 
   5708   if (p_dev_rec->p_callback) {
   5709     p_dev_rec->p_callback = NULL;
   5710 
   5711     if (is_le_transport)
   5712       (*p_callback)(&p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE,
   5713                     p_dev_rec->p_ref_data, res);
   5714     else
   5715       (*p_callback)(&p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR,
   5716                     p_dev_rec->p_ref_data, res);
   5717   }
   5718 
   5719   btm_sec_check_pending_reqs();
   5720 }
   5721 
   5722 /*******************************************************************************
   5723  *
   5724  * Function         btm_sec_queue_mx_request
   5725  *
   5726  * Description      Return state description for tracing
   5727  *
   5728  ******************************************************************************/
   5729 static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm,
   5730                                      bool is_orig, uint32_t mx_proto_id,
   5731                                      uint32_t mx_chan_id,
   5732                                      tBTM_SEC_CALLBACK* p_callback,
   5733                                      void* p_ref_data) {
   5734   tBTM_SEC_QUEUE_ENTRY* p_e =
   5735       (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY));
   5736 
   5737   p_e->psm = psm;
   5738   p_e->is_orig = is_orig;
   5739   p_e->p_callback = p_callback;
   5740   p_e->p_ref_data = p_ref_data;
   5741   p_e->mx_proto_id = mx_proto_id;
   5742   p_e->mx_chan_id = mx_chan_id;
   5743   p_e->transport = BT_TRANSPORT_BR_EDR;
   5744   p_e->sec_act = 0;
   5745   p_e->bd_addr = bd_addr;
   5746 
   5747   BTM_TRACE_EVENT(
   5748       "%s() PSM: 0x%04x  Is_Orig: %u  mx_proto_id: %u  mx_chan_id: %u",
   5749       __func__, psm, is_orig, mx_proto_id, mx_chan_id);
   5750 
   5751   fixed_queue_enqueue(btm_cb.sec_pending_q, p_e);
   5752 
   5753   return true;
   5754 }
   5755 
   5756 static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec) {
   5757   uint8_t major = (uint8_t)(p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK);
   5758   uint8_t minor = (uint8_t)(p_dev_rec->dev_class[2] & BTM_COD_MINOR_CLASS_MASK);
   5759   bool rv = false;
   5760 
   5761   if ((major == BTM_COD_MAJOR_AUDIO) &&
   5762       ((minor == BTM_COD_MINOR_CONFM_HANDSFREE) ||
   5763        (minor == BTM_COD_MINOR_CAR_AUDIO))) {
   5764     BTM_TRACE_EVENT(
   5765         "%s() Skipping pre-fetch PIN for carkit COD Major: 0x%02x Minor: "
   5766         "0x%02x",
   5767         __func__, major, minor);
   5768 
   5769     if (btm_cb.security_mode_changed == false) {
   5770       btm_cb.security_mode_changed = true;
   5771 #ifdef APPL_AUTH_WRITE_EXCEPTION
   5772       if (!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr))
   5773 #endif
   5774         btsnd_hcic_write_auth_enable(true);
   5775     }
   5776   } else {
   5777     btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN);
   5778 
   5779     /* If we got a PIN, use that, else try to get one */
   5780     if (btm_cb.pin_code_len) {
   5781       BTM_PINCodeReply(p_dev_rec->bd_addr, BTM_SUCCESS, btm_cb.pin_code_len,
   5782                        btm_cb.pin_code, p_dev_rec->trusted_mask);
   5783     } else {
   5784       /* pin was not supplied - pre-fetch pin code now */
   5785       if (btm_cb.api.p_pin_callback &&
   5786           ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0)) {
   5787         BTM_TRACE_DEBUG("%s() PIN code callback called", __func__);
   5788         if (btm_bda_to_acl(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR) == NULL)
   5789           btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
   5790         (btm_cb.api.p_pin_callback)(
   5791             p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name,
   5792             (p_dev_rec->p_cur_service == NULL)
   5793                 ? false
   5794                 : (p_dev_rec->p_cur_service->security_flags &
   5795                    BTM_SEC_IN_MIN_16_DIGIT_PIN));
   5796       }
   5797     }
   5798 
   5799     rv = true;
   5800   }
   5801 
   5802   return rv;
   5803 }
   5804 
   5805 /*******************************************************************************
   5806  *
   5807  * Function         btm_sec_auth_payload_tout
   5808  *
   5809  * Description      Processes the HCI Autheniticated Payload Timeout Event
   5810  *                  indicating that a packet containing a valid MIC on the
   5811  *                  connection handle was not received within the programmed
   5812  *                  timeout value. (Spec Default is 30 secs, but can be
   5813  *                  changed via the BTM_SecSetAuthPayloadTimeout() function.
   5814  *
   5815  ******************************************************************************/
   5816 void btm_sec_auth_payload_tout(uint8_t* p, uint16_t hci_evt_len) {
   5817   uint16_t handle;
   5818 
   5819   STREAM_TO_UINT16(handle, p);
   5820   handle = HCID_GET_HANDLE(handle);
   5821 
   5822   /* Will be exposed to upper layers in the future if/when determined necessary
   5823    */
   5824   BTM_TRACE_ERROR("%s on handle 0x%02x", __func__, handle);
   5825 }
   5826 
   5827 /*******************************************************************************
   5828  *
   5829  * Function         btm_sec_queue_encrypt_request
   5830  *
   5831  * Description      encqueue encryption request when device has active security
   5832  *                  process pending.
   5833  *
   5834  ******************************************************************************/
   5835 static bool btm_sec_queue_encrypt_request(const RawAddress& bd_addr,
   5836                                           tBT_TRANSPORT transport,
   5837                                           tBTM_SEC_CALLBACK* p_callback,
   5838                                           void* p_ref_data,
   5839                                           tBTM_BLE_SEC_ACT sec_act) {
   5840   tBTM_SEC_QUEUE_ENTRY* p_e =
   5841       (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY) + 1);
   5842 
   5843   p_e->psm = 0; /* if PSM 0, encryption request */
   5844   p_e->p_callback = p_callback;
   5845   p_e->p_ref_data = p_ref_data;
   5846   p_e->transport = transport;
   5847   p_e->sec_act = sec_act;
   5848   p_e->bd_addr = bd_addr;
   5849   fixed_queue_enqueue(btm_cb.sec_pending_q, p_e);
   5850 
   5851   return true;
   5852 }
   5853 
   5854 /*******************************************************************************
   5855  *
   5856  * Function         btm_sec_set_peer_sec_caps
   5857  *
   5858  * Description      This function is called to set sm4 and rmt_sec_caps fields
   5859  *                  based on the available peer device features.
   5860  *
   5861  * Returns          void
   5862  *
   5863  ******************************************************************************/
   5864 void btm_sec_set_peer_sec_caps(tACL_CONN* p_acl_cb,
   5865                                tBTM_SEC_DEV_REC* p_dev_rec) {
   5866   if ((btm_cb.security_mode == BTM_SEC_MODE_SP ||
   5867        btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
   5868        btm_cb.security_mode == BTM_SEC_MODE_SC) &&
   5869       HCI_SSP_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1])) {
   5870     p_dev_rec->sm4 = BTM_SM4_TRUE;
   5871     p_dev_rec->remote_supports_secure_connections =
   5872         (HCI_SC_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]));
   5873   } else {
   5874     p_dev_rec->sm4 = BTM_SM4_KNOWN;
   5875     p_dev_rec->remote_supports_secure_connections = false;
   5876   }
   5877 
   5878   BTM_TRACE_API("%s: sm4: 0x%02x, rmt_support_for_secure_connections %d",
   5879                 __func__, p_dev_rec->sm4,
   5880                 p_dev_rec->remote_supports_secure_connections);
   5881 
   5882   if (p_dev_rec->remote_features_needed) {
   5883     BTM_TRACE_EVENT(
   5884         "%s: Now device in SC Only mode, waiting for peer remote features!",
   5885         __func__);
   5886     btm_io_capabilities_req(p_dev_rec->bd_addr);
   5887     p_dev_rec->remote_features_needed = false;
   5888   }
   5889 }
   5890 
   5891 /*******************************************************************************
   5892  *
   5893  * Function         btm_sec_is_serv_level0
   5894  *
   5895  * Description      This function is called to check if the service
   5896  *                  corresponding to PSM is security mode 4 level 0 service.
   5897  *
   5898  * Returns          true if the service is security mode 4 level 0 service
   5899  *
   5900  ******************************************************************************/
   5901 static bool btm_sec_is_serv_level0(uint16_t psm) {
   5902   if (psm == BT_PSM_SDP) {
   5903     BTM_TRACE_DEBUG("%s: PSM: 0x%04x -> mode 4 level 0 service", __func__, psm);
   5904     return true;
   5905   }
   5906   return false;
   5907 }
   5908 
   5909 /*******************************************************************************
   5910  *
   5911  * Function         btm_sec_check_pending_enc_req
   5912  *
   5913  * Description      This function is called to send pending encryption callback
   5914  *                  if waiting
   5915  *
   5916  * Returns          void
   5917  *
   5918  ******************************************************************************/
   5919 static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec,
   5920                                           tBT_TRANSPORT transport,
   5921                                           uint8_t encr_enable) {
   5922   if (fixed_queue_is_empty(btm_cb.sec_pending_q)) return;
   5923 
   5924   uint8_t res = encr_enable ? BTM_SUCCESS : BTM_ERR_PROCESSING;
   5925   list_t* list = fixed_queue_get_list(btm_cb.sec_pending_q);
   5926   for (const list_node_t* node = list_begin(list); node != list_end(list);) {
   5927     tBTM_SEC_QUEUE_ENTRY* p_e = (tBTM_SEC_QUEUE_ENTRY*)list_node(node);
   5928     node = list_next(node);
   5929 
   5930     if (p_e->bd_addr == p_dev_rec->bd_addr && p_e->psm == 0 &&
   5931         p_e->transport == transport) {
   5932       if (encr_enable == 0 || transport == BT_TRANSPORT_BR_EDR ||
   5933           p_e->sec_act == BTM_BLE_SEC_ENCRYPT ||
   5934           p_e->sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM ||
   5935           (p_e->sec_act == BTM_BLE_SEC_ENCRYPT_MITM &&
   5936            p_dev_rec->sec_flags & BTM_SEC_LE_AUTHENTICATED)) {
   5937         if (p_e->p_callback)
   5938           (*p_e->p_callback)(&p_dev_rec->bd_addr, transport, p_e->p_ref_data,
   5939                              res);
   5940         fixed_queue_try_remove_from_queue(btm_cb.sec_pending_q, (void*)p_e);
   5941       }
   5942     }
   5943   }
   5944 }
   5945 
   5946 /*******************************************************************************
   5947  *
   5948  * Function         btm_sec_set_serv_level4_flags
   5949  *
   5950  * Description      This function is called to set security mode 4 level 4
   5951  *                  flags.
   5952  *
   5953  * Returns          service security requirements updated to include secure
   5954  *                  connections only mode.
   5955  *
   5956  ******************************************************************************/
   5957 static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security,
   5958                                               bool is_originator) {
   5959   uint16_t sec_level4_flags =
   5960       is_originator ? BTM_SEC_OUT_LEVEL4_FLAGS : BTM_SEC_IN_LEVEL4_FLAGS;
   5961 
   5962   return cur_security | sec_level4_flags;
   5963 }
   5964 
   5965 /*******************************************************************************
   5966  *
   5967  * Function         btm_sec_clear_ble_keys
   5968  *
   5969  * Description      This function is called to clear out the BLE keys.
   5970  *                  Typically when devices are removed in BTM_SecDeleteDevice,
   5971  *                  or when a new BT Link key is generated.
   5972  *
   5973  * Returns          void
   5974  *
   5975  ******************************************************************************/
   5976 void btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC* p_dev_rec) {
   5977   BTM_TRACE_DEBUG("%s() Clearing BLE Keys", __func__);
   5978   p_dev_rec->ble.key_type = BTM_LE_KEY_NONE;
   5979   memset(&p_dev_rec->ble.keys, 0, sizeof(tBTM_SEC_BLE_KEYS));
   5980 
   5981 #if (BLE_PRIVACY_SPT == TRUE)
   5982   btm_ble_resolving_list_remove_dev(p_dev_rec);
   5983 #endif
   5984 }
   5985 
   5986 /*******************************************************************************
   5987  *
   5988  * Function         btm_sec_is_a_bonded_dev
   5989  *
   5990  * Description       Is the specified device is a bonded device
   5991  *
   5992  * Returns          true - dev is bonded
   5993  *
   5994  ******************************************************************************/
   5995 bool btm_sec_is_a_bonded_dev(const RawAddress& bda) {
   5996   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
   5997   bool is_bonded = false;
   5998 
   5999   if (p_dev_rec && ((p_dev_rec->ble.key_type &&
   6000                      (p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN)) ||
   6001                     (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN))) {
   6002     is_bonded = true;
   6003   }
   6004   BTM_TRACE_DEBUG("%s() is_bonded=%d", __func__, is_bonded);
   6005   return (is_bonded);
   6006 }
   6007 
   6008 /*******************************************************************************
   6009  *
   6010  * Function         btm_sec_is_le_capable_dev
   6011  *
   6012  * Description       Is the specified device is dual mode or LE only device
   6013  *
   6014  * Returns          true - dev is a dual mode
   6015  *
   6016  ******************************************************************************/
   6017 bool btm_sec_is_le_capable_dev(const RawAddress& bda) {
   6018   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
   6019   bool le_capable = false;
   6020 
   6021   if (p_dev_rec &&
   6022       (p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE)
   6023     le_capable = true;
   6024   return le_capable;
   6025 }
   6026 
   6027 /*******************************************************************************
   6028  *
   6029  * Function         btm_sec_use_smp_br_chnl
   6030  *
   6031  * Description      The function checks if SMP BR connection can be used with
   6032  *                  the peer.
   6033  *                  Is called when authentication for dedicated bonding is
   6034  *                  successfully completed.
   6035  *
   6036  * Returns          true - if SMP BR connection can be used (the link key is
   6037  *                         generated from P-256 and the peer supports Security
   6038  *                         Manager over BR).
   6039  *
   6040  ******************************************************************************/
   6041 static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec) {
   6042   uint32_t ext_feat;
   6043   uint8_t chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE];
   6044 
   6045   BTM_TRACE_DEBUG("%s() link_key_type = 0x%x", __func__,
   6046                   p_dev_rec->link_key_type);
   6047 
   6048   if ((p_dev_rec->link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256) &&
   6049       (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
   6050     return false;
   6051 
   6052   if (!L2CA_GetPeerFeatures(p_dev_rec->bd_addr, &ext_feat, chnl_mask))
   6053     return false;
   6054 
   6055   if (!(chnl_mask[0] & L2CAP_FIXED_CHNL_SMP_BR_BIT)) return false;
   6056 
   6057   return true;
   6058 }
   6059 
   6060 /*******************************************************************************
   6061  *
   6062  * Function         btm_sec_is_master
   6063  *
   6064  * Description      The function checks if the device is BR/EDR master after
   6065  *                  pairing is completed.
   6066  *
   6067  * Returns          true - if the device is master.
   6068  *
   6069  ******************************************************************************/
   6070 static bool btm_sec_is_master(tBTM_SEC_DEV_REC* p_dev_rec) {
   6071   tACL_CONN* p = btm_bda_to_acl(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR);
   6072   return (p && (p->link_role == BTM_ROLE_MASTER));
   6073 }
   6074