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