btif_dm.c revision 64c5479fc050c537ef6d39625de2032c77fc5676
1/******************************************************************************
2 *
3 *  Copyright (C) 2009-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 *  Filename:      btif_dm.c
22 *
23 *  Description:   Contains Device Management (DM) related functionality
24 *
25 *
26 ***********************************************************************************/
27#include <stdio.h>
28#include <stdlib.h>
29#include <unistd.h>
30
31#include <hardware/bluetooth.h>
32
33#include <utils/Log.h>
34#include <cutils/properties.h>
35#include "gki.h"
36#include "btu.h"
37#include "bd.h"
38#include "bta_api.h"
39#include "btif_api.h"
40#include "btif_util.h"
41#include "btif_dm.h"
42#include "btif_storage.h"
43#include "btif_hh.h"
44#include "btif_config.h"
45
46#include "bta_gatt_api.h"
47/******************************************************************************
48**  Constants & Macros
49******************************************************************************/
50
51#define COD_UNCLASSIFIED ((0x1F) << 8)
52#define COD_HID_KEYBOARD                    0x0540
53#define COD_HID_POINTING                    0x0580
54#define COD_HID_COMBO                       0x05C0
55#define COD_HID_MAJOR                       0x0500
56#define COD_AV_HEADSETS                     0x0404
57#define COD_AV_HANDSFREE                    0x0408
58#define COD_AV_HEADPHONES                   0x0418
59#define COD_AV_PORTABLE_AUDIO               0x041C
60#define COD_AV_HIFI_AUDIO                   0x0428
61
62
63#define BTIF_DM_DEFAULT_INQ_MAX_RESULTS     0
64#define BTIF_DM_DEFAULT_INQ_MAX_DURATION    10
65#define BTIF_DM_MAX_SDP_ATTEMPTS_AFTER_PAIRING 2
66
67#define PROPERTY_PRODUCT_MODEL "ro.product.model"
68#define DEFAULT_LOCAL_NAME_MAX  31
69#if (DEFAULT_LOCAL_NAME_MAX > BTM_MAX_LOC_BD_NAME_LEN)
70    #error "default btif local name size exceeds stack supported length"
71#endif
72
73#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE)
74#define BTIF_DM_INTERLEAVE_DURATION_BR_ONE    2
75#define BTIF_DM_INTERLEAVE_DURATION_LE_ONE    2
76#define BTIF_DM_INTERLEAVE_DURATION_BR_TWO    3
77#define BTIF_DM_INTERLEAVE_DURATION_LE_TWO    4
78#endif
79
80#define MAX_SDP_BL_ENTRIES 3
81
82typedef struct
83{
84    bt_bond_state_t state;
85    BD_ADDR bd_addr;
86    UINT8   is_temp;
87    UINT8   pin_code_len;
88    UINT8   is_ssp;
89    UINT8   auth_req;
90    UINT8   io_cap;
91    UINT8   autopair_attempts;
92    UINT8   is_local_initiated;
93    UINT8   sdp_attempts;
94#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
95    BOOLEAN          is_le_only;
96    btif_dm_ble_cb_t ble;
97#endif
98} btif_dm_pairing_cb_t;
99
100
101typedef struct
102{
103    UINT8       ir[BT_OCTET16_LEN];
104    UINT8       irk[BT_OCTET16_LEN];
105    UINT8       dhk[BT_OCTET16_LEN];
106}btif_dm_local_key_id_t;
107
108typedef struct
109{
110    BOOLEAN                 is_er_rcvd;
111    UINT8                   er[BT_OCTET16_LEN];
112    BOOLEAN                 is_id_keys_rcvd;
113    btif_dm_local_key_id_t  id_keys;  /* ID kyes */
114
115}btif_dm_local_key_cb_t;
116
117typedef struct
118{
119    BD_ADDR bd_addr;
120    BD_NAME bd_name;
121} btif_dm_remote_name_t;
122
123typedef struct
124{
125    BT_OCTET16 sp_c;
126    BT_OCTET16 sp_r;
127    BD_ADDR  oob_bdaddr;  /* peer bdaddr*/
128} btif_dm_oob_cb_t;
129
130typedef struct
131{
132    bt_bdaddr_t  bdaddr;
133    UINT8        transport; /* 0=Unknown, 1=BR/EDR, 2=LE */
134} btif_dm_create_bond_cb_t;
135
136typedef struct
137{
138    uint8_t  status;
139    uint8_t  ctrl_state;
140    uint64_t tx_time;
141    uint64_t rx_time;
142    uint64_t idle_time;
143    uint64_t energy_used;
144} btif_activity_energy_info_cb_t;
145
146typedef struct
147{
148    unsigned int   manufact_id;
149}skip_sdp_entry_t;
150
151#define BTA_SERVICE_ID_TO_SERVICE_MASK(id)       (1 << (id))
152
153#define MAX_SDP_BL_ENTRIES 3
154#define UUID_HUMAN_INTERFACE_DEVICE "00001124-0000-1000-8000-00805f9b34fb"
155
156static skip_sdp_entry_t sdp_blacklist[] = {{76}}; //Apple Mouse and Keyboard
157
158
159/* This flag will be true if HCI_Inquiry is in progress */
160static BOOLEAN btif_dm_inquiry_in_progress = FALSE;
161
162
163
164/************************************************************************************
165**  Static variables
166************************************************************************************/
167static char btif_default_local_name[DEFAULT_LOCAL_NAME_MAX+1] = {'\0'};
168
169/******************************************************************************
170**  Static functions
171******************************************************************************/
172static btif_dm_pairing_cb_t pairing_cb;
173static btif_dm_oob_cb_t     oob_cb;
174static void btif_dm_generic_evt(UINT16 event, char* p_param);
175static void btif_dm_cb_create_bond(bt_bdaddr_t *bd_addr, tBTA_TRANSPORT transport);
176static void btif_dm_cb_hid_remote_name(tBTM_REMOTE_DEV_NAME *p_remote_name);
177static void btif_update_remote_properties(BD_ADDR bd_addr, BD_NAME bd_name,
178                                          DEV_CLASS dev_class, tBT_DEVICE_TYPE dev_type);
179#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
180static btif_dm_local_key_cb_t ble_local_key_cb;
181static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF *p_ssp_key_notif);
182static void btif_dm_ble_auth_cmpl_evt (tBTA_DM_AUTH_CMPL *p_auth_cmpl);
183static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ *p_pin_req);
184#endif
185
186static void bte_scan_filt_param_cfg_evt(UINT8 action_type,
187                                           tBTA_DM_BLE_PF_AVBL_SPACE avbl_space,
188                                           tBTA_DM_BLE_REF_VALUE ref_value, tBTA_STATUS status);
189
190static char* btif_get_default_local_name();
191/******************************************************************************
192**  Externs
193******************************************************************************/
194extern UINT16 bta_service_id_to_uuid_lkup_tbl [BTA_MAX_SERVICE_ID];
195extern bt_status_t btif_hf_execute_service(BOOLEAN b_enable);
196extern bt_status_t btif_av_execute_service(BOOLEAN b_enable);
197extern bt_status_t btif_hh_execute_service(BOOLEAN b_enable);
198extern bt_status_t btif_hf_client_execute_service(BOOLEAN b_enable);
199extern bt_status_t btif_mce_execute_service(BOOLEAN b_enable);
200extern int btif_hh_connect(bt_bdaddr_t *bd_addr);
201extern void bta_gatt_convert_uuid16_to_uuid128(UINT8 uuid_128[LEN_UUID_128], UINT16 uuid_16);
202
203
204/******************************************************************************
205**  Functions
206******************************************************************************/
207
208bt_status_t btif_in_execute_service_request(tBTA_SERVICE_ID service_id,
209                                                BOOLEAN b_enable)
210{
211    /* Check the service_ID and invoke the profile's BT state changed API */
212    switch (service_id)
213    {
214         case BTA_HFP_SERVICE_ID:
215         case BTA_HSP_SERVICE_ID:
216         {
217              btif_hf_execute_service(b_enable);
218         }break;
219         case BTA_A2DP_SERVICE_ID:
220         {
221              btif_av_execute_service(b_enable);
222         }break;
223         case BTA_HID_SERVICE_ID:
224         {
225              btif_hh_execute_service(b_enable);
226         }break;
227         case BTA_HFP_HS_SERVICE_ID:
228         {
229             btif_hf_client_execute_service(b_enable);
230         }break;
231         case BTA_MAP_SERVICE_ID:
232         {
233             btif_mce_execute_service(b_enable);
234         }break;
235         default:
236              BTIF_TRACE_ERROR("%s: Unknown service being enabled", __FUNCTION__);
237              return BT_STATUS_FAIL;
238    }
239    return BT_STATUS_SUCCESS;
240}
241
242/*******************************************************************************
243**
244** Function         check_eir_remote_name
245**
246** Description      Check if remote name is in the EIR data
247**
248** Returns          TRUE if remote name found
249**                  Populate p_remote_name, if provided and remote name found
250**
251*******************************************************************************/
252static BOOLEAN check_eir_remote_name(tBTA_DM_SEARCH *p_search_data,
253                            UINT8 *p_remote_name, UINT8 *p_remote_name_len)
254{
255    UINT8 *p_eir_remote_name = NULL;
256    UINT8 remote_name_len = 0;
257
258    /* Check EIR for remote name and services */
259    if (p_search_data->inq_res.p_eir)
260    {
261        p_eir_remote_name = BTA_CheckEirData(p_search_data->inq_res.p_eir,
262                BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
263        if (!p_eir_remote_name)
264        {
265            p_eir_remote_name = BTA_CheckEirData(p_search_data->inq_res.p_eir,
266                    BTM_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
267        }
268
269        if (p_eir_remote_name)
270        {
271            if (remote_name_len > BD_NAME_LEN)
272                remote_name_len = BD_NAME_LEN;
273
274            if (p_remote_name && p_remote_name_len)
275            {
276                memcpy(p_remote_name, p_eir_remote_name, remote_name_len);
277                *(p_remote_name + remote_name_len) = 0;
278                *p_remote_name_len = remote_name_len;
279            }
280
281            return TRUE;
282        }
283    }
284
285    return FALSE;
286
287}
288
289/*******************************************************************************
290**
291** Function         check_cached_remote_name
292**
293** Description      Check if remote name is in the NVRAM cache
294**
295** Returns          TRUE if remote name found
296**                  Populate p_remote_name, if provided and remote name found
297**
298*******************************************************************************/
299static BOOLEAN check_cached_remote_name(tBTA_DM_SEARCH *p_search_data,
300                                UINT8 *p_remote_name, UINT8 *p_remote_name_len)
301{
302    bt_bdname_t bdname;
303    bt_bdaddr_t remote_bdaddr;
304    bt_property_t prop_name;
305
306    /* check if we already have it in our btif_storage cache */
307    bdcpy(remote_bdaddr.address, p_search_data->inq_res.bd_addr);
308    BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME,
309                               sizeof(bt_bdname_t), &bdname);
310    if (btif_storage_get_remote_device_property(
311        &remote_bdaddr, &prop_name) == BT_STATUS_SUCCESS)
312    {
313        if (p_remote_name && p_remote_name_len)
314        {
315            strcpy((char *)p_remote_name, (char *)bdname.name);
316            *p_remote_name_len = strlen((char *)p_remote_name);
317        }
318        return TRUE;
319    }
320
321    return FALSE;
322}
323
324BOOLEAN check_cod(const bt_bdaddr_t *remote_bdaddr, uint32_t cod)
325{
326    uint32_t    remote_cod;
327    bt_property_t prop_name;
328
329    /* check if we already have it in our btif_storage cache */
330    BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE,
331                               sizeof(uint32_t), &remote_cod);
332    if (btif_storage_get_remote_device_property((bt_bdaddr_t *)remote_bdaddr, &prop_name) == BT_STATUS_SUCCESS)
333    {
334        BTIF_TRACE_ERROR("%s: remote_cod = 0x%06x", __FUNCTION__, remote_cod);
335        if ((remote_cod & 0x7ff) == cod)
336            return TRUE;
337    }
338
339    return FALSE;
340}
341
342BOOLEAN check_cod_hid(const bt_bdaddr_t *remote_bdaddr, uint32_t cod)
343{
344    uint32_t    remote_cod;
345    bt_property_t prop_name;
346
347    /* check if we already have it in our btif_storage cache */
348    BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE,
349                               sizeof(uint32_t), &remote_cod);
350    if (btif_storage_get_remote_device_property((bt_bdaddr_t *)remote_bdaddr,
351                                &prop_name) == BT_STATUS_SUCCESS)
352    {
353        BTIF_TRACE_DEBUG("%s: remote_cod = 0x%06x", __FUNCTION__, remote_cod);
354        if ((remote_cod & 0x700) == cod)
355            return TRUE;
356    }
357    return FALSE;
358}
359
360BOOLEAN check_hid_le(const bt_bdaddr_t *remote_bdaddr)
361{
362    uint32_t    remote_dev_type;
363    bt_property_t prop_name;
364
365    /* check if we already have it in our btif_storage cache */
366    BTIF_STORAGE_FILL_PROPERTY(&prop_name,BT_PROPERTY_TYPE_OF_DEVICE,
367                               sizeof(uint32_t), &remote_dev_type);
368    if (btif_storage_get_remote_device_property((bt_bdaddr_t *)remote_bdaddr,
369                                &prop_name) == BT_STATUS_SUCCESS)
370    {
371        if (remote_dev_type == BT_DEVICE_DEVTYPE_BLE)
372        {
373            bdstr_t bdstr;
374            bd2str(remote_bdaddr, &bdstr);
375            if(btif_config_exist("Remote", bdstr, "HidAppId"))
376                return TRUE;
377        }
378    }
379    return FALSE;
380}
381
382/*****************************************************************************
383**
384** Function        check_sdp_bl
385**
386** Description     Checks if a given device is blacklisted to skip sdp
387**
388** Parameters     skip_sdp_entry
389**
390** Returns         TRUE if the device is present in blacklist, else FALSE
391**
392*******************************************************************************/
393BOOLEAN check_sdp_bl(const bt_bdaddr_t *remote_bdaddr)
394{
395    UINT8 i = 0;
396    UINT16 manufacturer = 0;
397    UINT8 lmp_ver = 0;
398    UINT16 lmp_subver = 0;
399    tBTM_STATUS btm_status;
400    bt_property_t prop_name;
401    bt_remote_version_t info;
402    bt_status_t status;
403
404
405    if (remote_bdaddr == NULL)
406        return FALSE;
407
408/* fetch additional info about remote device used in iop query */
409    btm_status = BTM_ReadRemoteVersion(*(BD_ADDR*)remote_bdaddr, &lmp_ver,
410                    &manufacturer, &lmp_subver);
411
412
413
414 /* if not available yet, try fetching from config database */
415    BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_REMOTE_VERSION_INFO,
416                            sizeof(bt_remote_version_t), &info);
417
418    if (btif_storage_get_remote_device_property((bt_bdaddr_t *)remote_bdaddr,
419                                              &prop_name) != BT_STATUS_SUCCESS)
420    {
421
422        return FALSE;
423    }
424    manufacturer = info.manufacturer;
425
426    for (int i = 0; i < MAX_SDP_BL_ENTRIES; i++)
427    {
428        if (manufacturer == sdp_blacklist[i].manufact_id)
429            return TRUE;
430    }
431    return FALSE;
432}
433
434
435static void bond_state_changed(bt_status_t status, bt_bdaddr_t *bd_addr, bt_bond_state_t state)
436{
437    /* Send bonding state only once - based on outgoing/incoming we may receive duplicates */
438    if ( (pairing_cb.state == state) && (state == BT_BOND_STATE_BONDING) )
439        return;
440
441    if (pairing_cb.is_temp)
442    {
443       state = BT_BOND_STATE_NONE;
444    }
445    BTIF_TRACE_DEBUG("%s: state=%d prev_state=%d", __FUNCTION__, state, pairing_cb.state);
446
447    HAL_CBACK(bt_hal_cbacks, bond_state_changed_cb, status, bd_addr, state);
448
449    if (state == BT_BOND_STATE_BONDING)
450    {
451        pairing_cb.state = state;
452        bdcpy(pairing_cb.bd_addr, bd_addr->address);
453    }
454    else
455    {
456        memset(&pairing_cb, 0, sizeof(pairing_cb));
457    }
458
459}
460
461/* store remote version in bt config to always have access
462   to it post pairing*/
463static void btif_update_remote_version_property(bt_bdaddr_t *p_bd)
464{
465    bt_property_t property;
466    UINT8 lmp_ver = 0;
467    UINT16 lmp_subver = 0;
468    UINT16 mfct_set = 0;
469    tBTM_STATUS btm_status;
470    bt_remote_version_t info;
471    bt_status_t status;
472    bdstr_t bdstr;
473
474    btm_status = BTM_ReadRemoteVersion(*(BD_ADDR*)p_bd, &lmp_ver,
475                          &mfct_set, &lmp_subver);
476
477    ALOGD("remote version info [%s]: %x, %x, %x", bd2str(p_bd, &bdstr),
478               lmp_ver, mfct_set, lmp_subver);
479
480    if (btm_status == BTM_SUCCESS)
481    {
482        /* always update cache to ensure we have availability whenever BTM API
483           is not populated */
484        info.manufacturer = mfct_set;
485        info.sub_ver = lmp_subver;
486        info.version = lmp_ver;
487        BTIF_STORAGE_FILL_PROPERTY(&property,
488                            BT_PROPERTY_REMOTE_VERSION_INFO, sizeof(bt_remote_version_t),
489                            &info);
490        status = btif_storage_set_remote_device_property(p_bd, &property);
491        ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote version", status);
492    }
493}
494
495
496static void btif_update_remote_properties(BD_ADDR bd_addr, BD_NAME bd_name,
497                                          DEV_CLASS dev_class, tBT_DEVICE_TYPE device_type)
498{
499    int num_properties = 0;
500    bt_property_t properties[3];
501    bt_bdaddr_t bdaddr;
502    bt_status_t status;
503    UINT32 cod;
504    bt_device_type_t dev_type;
505
506    memset(properties, 0, sizeof(properties));
507    bdcpy(bdaddr.address, bd_addr);
508
509    /* remote name */
510    if (strlen((const char *) bd_name))
511    {
512        BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
513                            BT_PROPERTY_BDNAME, strlen((char *)bd_name), bd_name);
514        status = btif_storage_set_remote_device_property(&bdaddr, &properties[num_properties]);
515        ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device name", status);
516        num_properties++;
517    }
518
519    /* class of device */
520    cod = devclass2uint(dev_class);
521    BTIF_TRACE_DEBUG("%s():cod is 0x%06x", __FUNCTION__, cod);
522    if ( cod == 0) {
523       /* Try to retrieve cod from storage */
524        BTIF_TRACE_DEBUG("%s():cod is 0, checking cod from storage", __FUNCTION__);
525        BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
526            BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
527        status = btif_storage_get_remote_device_property(&bdaddr, &properties[num_properties]);
528        BTIF_TRACE_DEBUG("%s():cod retreived from storage is 0x%06x", __FUNCTION__, cod);
529        if ( cod == 0) {
530            BTIF_TRACE_DEBUG("%s():cod is again 0, set as unclassified", __FUNCTION__);
531            cod = COD_UNCLASSIFIED;
532        }
533    }
534
535    BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
536                        BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
537    status = btif_storage_set_remote_device_property(&bdaddr, &properties[num_properties]);
538    ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device class", status);
539    num_properties++;
540
541    /* device type */
542    dev_type = device_type;
543    BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
544                        BT_PROPERTY_TYPE_OF_DEVICE, sizeof(dev_type), &dev_type);
545    status = btif_storage_set_remote_device_property(&bdaddr, &properties[num_properties]);
546    ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device type", status);
547    num_properties++;
548
549    HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
550                     status, &bdaddr, num_properties, properties);
551}
552
553/*******************************************************************************
554**
555** Function         btif_dm_cb_hid_remote_name
556**
557** Description      Remote name callback for HID device. Called in btif context
558**                  Special handling for HID devices
559**
560** Returns          void
561**
562*******************************************************************************/
563static void btif_dm_cb_hid_remote_name(tBTM_REMOTE_DEV_NAME *p_remote_name)
564{
565    BTIF_TRACE_DEBUG("%s: status=%d pairing_cb.state=%d", __FUNCTION__, p_remote_name->status, pairing_cb.state);
566    if (pairing_cb.state == BT_BOND_STATE_BONDING)
567    {
568        bt_bdaddr_t remote_bd;
569
570        bdcpy(remote_bd.address, pairing_cb.bd_addr);
571
572        if (p_remote_name->status == BTM_SUCCESS)
573        {
574            bond_state_changed(BT_STATUS_SUCCESS, &remote_bd, BT_BOND_STATE_BONDED);
575        }
576        else
577            bond_state_changed(BT_STATUS_FAIL, &remote_bd, BT_BOND_STATE_NONE);
578    }
579}
580
581/*******************************************************************************
582**
583** Function         btif_dm_cb_create_bond
584**
585** Description      Create bond initiated from the BTIF thread context
586**                  Special handling for HID devices
587**
588** Returns          void
589**
590*******************************************************************************/
591static void btif_dm_cb_create_bond(bt_bdaddr_t *bd_addr, tBTA_TRANSPORT transport)
592{
593    BOOLEAN is_hid = check_cod(bd_addr, COD_HID_POINTING);
594    bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
595
596#if BLE_INCLUDED == TRUE
597    int device_type;
598    int addr_type;
599    bdstr_t bdstr;
600    bd2str(bd_addr, &bdstr);
601    if (transport == BT_TRANSPORT_LE)
602    {
603        if (!btif_config_get_int("Remote", (char const *)&bdstr,"DevType", &device_type))
604        {
605            btif_config_set_int("Remote", bdstr, "DevType", BT_DEVICE_TYPE_BLE);
606        }
607        if (btif_storage_get_remote_addr_type(bd_addr, &addr_type) != BT_STATUS_SUCCESS)
608        {
609            btif_storage_set_remote_addr_type(bd_addr, BLE_ADDR_PUBLIC);
610        }
611    }
612    if((btif_config_get_int("Remote", (char const *)&bdstr,"DevType", &device_type) &&
613       (btif_storage_get_remote_addr_type(bd_addr, &addr_type) == BT_STATUS_SUCCESS) &&
614       (device_type == BT_DEVICE_TYPE_BLE)) || (transport == BT_TRANSPORT_LE))
615    {
616        BTA_DmAddBleDevice(bd_addr->address, addr_type, BT_DEVICE_TYPE_BLE);
617    }
618#endif
619
620#if BLE_INCLUDED == TRUE
621    if(is_hid && device_type != BT_DEVICE_TYPE_BLE)
622#else
623    if(is_hid)
624#endif
625    {
626        int status;
627        status = btif_hh_connect(bd_addr);
628        if(status != BT_STATUS_SUCCESS)
629            bond_state_changed(status, bd_addr, BT_BOND_STATE_NONE);
630    }
631    else
632    {
633        BTA_DmBondByTransport((UINT8 *)bd_addr->address, transport);
634    }
635    /*  Track  originator of bond creation  */
636    pairing_cb.is_local_initiated = TRUE;
637
638}
639
640/*******************************************************************************
641**
642** Function         btif_dm_cb_remove_bond
643**
644** Description      remove bond initiated from the BTIF thread context
645**                  Special handling for HID devices
646**
647** Returns          void
648**
649*******************************************************************************/
650void btif_dm_cb_remove_bond(bt_bdaddr_t *bd_addr)
651{
652     bdstr_t bdstr;
653     /*special handling for HID devices */
654     /*  VUP needs to be sent if its a HID Device. The HID HOST module will check if there
655     is a valid hid connection with this bd_addr. If yes VUP will be issued.*/
656#if (defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE))
657    if (btif_hh_virtual_unplug(bd_addr) != BT_STATUS_SUCCESS)
658#endif
659    {
660         BTA_DmRemoveDevice((UINT8 *)bd_addr->address);
661    }
662}
663
664/*******************************************************************************
665**
666** Function         btif_dm_get_connection_state
667**
668** Description      Returns whether the remote device is currently connected
669**
670** Returns          0 if not connected
671**
672*******************************************************************************/
673uint16_t btif_dm_get_connection_state(const bt_bdaddr_t *bd_addr)
674{
675    return BTA_DmGetConnectionState((UINT8 *)bd_addr->address);
676}
677
678/*******************************************************************************
679**
680** Function         search_devices_copy_cb
681**
682** Description      Deep copy callback for search devices event
683**
684** Returns          void
685**
686*******************************************************************************/
687static void search_devices_copy_cb(UINT16 event, char *p_dest, char *p_src)
688{
689    tBTA_DM_SEARCH *p_dest_data =  (tBTA_DM_SEARCH *) p_dest;
690    tBTA_DM_SEARCH *p_src_data =  (tBTA_DM_SEARCH *) p_src;
691
692    if (!p_src)
693        return;
694
695    BTIF_TRACE_DEBUG("%s: event=%s", __FUNCTION__, dump_dm_search_event(event));
696    memcpy(p_dest_data, p_src_data, sizeof(tBTA_DM_SEARCH));
697    switch (event)
698    {
699        case BTA_DM_INQ_RES_EVT:
700        {
701            if (p_src_data->inq_res.p_eir)
702            {
703                p_dest_data->inq_res.p_eir = (UINT8 *)(p_dest + sizeof(tBTA_DM_SEARCH));
704                memcpy(p_dest_data->inq_res.p_eir, p_src_data->inq_res.p_eir, HCI_EXT_INQ_RESPONSE_LEN);
705            }
706        }
707        break;
708
709        case BTA_DM_DISC_RES_EVT:
710        {
711            if (p_src_data->disc_res.raw_data_size && p_src_data->disc_res.p_raw_data)
712            {
713                p_dest_data->disc_res.p_raw_data = (UINT8 *)(p_dest + sizeof(tBTA_DM_SEARCH));
714                memcpy(p_dest_data->disc_res.p_raw_data,
715                    p_src_data->disc_res.p_raw_data, p_src_data->disc_res.raw_data_size);
716            }
717        }
718        break;
719    }
720}
721
722static void search_services_copy_cb(UINT16 event, char *p_dest, char *p_src)
723{
724    tBTA_DM_SEARCH *p_dest_data =  (tBTA_DM_SEARCH *) p_dest;
725    tBTA_DM_SEARCH *p_src_data =  (tBTA_DM_SEARCH *) p_src;
726
727    if (!p_src)
728        return;
729    memcpy(p_dest_data, p_src_data, sizeof(tBTA_DM_SEARCH));
730    switch (event)
731    {
732         case BTA_DM_DISC_RES_EVT:
733         {
734              if (p_src_data->disc_res.result == BTA_SUCCESS)
735              {
736                  if (p_src_data->disc_res.num_uuids > 0)
737                  {
738                       p_dest_data->disc_res.p_uuid_list =
739                                                        (UINT8*)(p_dest + sizeof(tBTA_DM_SEARCH));
740                       memcpy(p_dest_data->disc_res.p_uuid_list, p_src_data->disc_res.p_uuid_list,
741                              p_src_data->disc_res.num_uuids*MAX_UUID_SIZE);
742                       GKI_freebuf(p_src_data->disc_res.p_uuid_list);
743                  }
744                  if (p_src_data->disc_res.p_raw_data != NULL)
745                  {
746                      GKI_freebuf(p_src_data->disc_res.p_raw_data);
747                  }
748              }
749         } break;
750    }
751}
752/******************************************************************************
753**
754**  BTIF DM callback events
755**
756*****************************************************************************/
757
758/*******************************************************************************
759**
760** Function         btif_dm_pin_req_evt
761**
762** Description      Executes pin request event in btif context
763**
764** Returns          void
765**
766*******************************************************************************/
767static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ *p_pin_req)
768{
769    bt_bdaddr_t bd_addr;
770    bt_bdname_t bd_name;
771    UINT32 cod;
772    bt_pin_code_t pin_code;
773
774    /* Remote properties update */
775    btif_update_remote_properties(p_pin_req->bd_addr, p_pin_req->bd_name,
776                                  p_pin_req->dev_class, BT_DEVICE_TYPE_BREDR);
777
778    bdcpy(bd_addr.address, p_pin_req->bd_addr);
779    memcpy(bd_name.name, p_pin_req->bd_name, BD_NAME_LEN);
780
781    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
782
783    cod = devclass2uint(p_pin_req->dev_class);
784
785    if ( cod == 0) {
786        BTIF_TRACE_DEBUG("%s():cod is 0, set as unclassified", __FUNCTION__);
787        cod = COD_UNCLASSIFIED;
788    }
789
790    /* check for auto pair possiblity only if bond was initiated by local device */
791    if (pairing_cb.is_local_initiated)
792    {
793        if (check_cod(&bd_addr, COD_AV_HEADSETS) ||
794            check_cod(&bd_addr, COD_AV_HANDSFREE) ||
795            check_cod(&bd_addr, COD_AV_HEADPHONES) ||
796            check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) ||
797            check_cod(&bd_addr, COD_AV_HIFI_AUDIO) ||
798            check_cod(&bd_addr, COD_HID_POINTING))
799        {
800            BTIF_TRACE_DEBUG("%s()cod matches for auto pair", __FUNCTION__);
801            /*  Check if this device can be auto paired  */
802            if ((btif_storage_is_device_autopair_blacklisted(&bd_addr) == FALSE) &&
803                (pairing_cb.autopair_attempts == 0))
804            {
805                BTIF_TRACE_DEBUG("%s() Attempting auto pair", __FUNCTION__);
806                pin_code.pin[0] = 0x30;
807                pin_code.pin[1] = 0x30;
808                pin_code.pin[2] = 0x30;
809                pin_code.pin[3] = 0x30;
810
811                pairing_cb.autopair_attempts++;
812                BTA_DmPinReply( (UINT8*)bd_addr.address, TRUE, 4, pin_code.pin);
813                return;
814            }
815        }
816        else if (check_cod(&bd_addr, COD_HID_KEYBOARD) ||
817                 check_cod(&bd_addr, COD_HID_COMBO))
818        {
819            if(( btif_storage_is_fixed_pin_zeros_keyboard (&bd_addr) == TRUE) &&
820               (pairing_cb.autopair_attempts == 0))
821            {
822                BTIF_TRACE_DEBUG("%s() Attempting auto pair", __FUNCTION__);
823                pin_code.pin[0] = 0x30;
824                pin_code.pin[1] = 0x30;
825                pin_code.pin[2] = 0x30;
826                pin_code.pin[3] = 0x30;
827
828                pairing_cb.autopair_attempts++;
829                BTA_DmPinReply( (UINT8*)bd_addr.address, TRUE, 4, pin_code.pin);
830                return;
831            }
832        }
833    }
834    HAL_CBACK(bt_hal_cbacks, pin_request_cb,
835                     &bd_addr, &bd_name, cod);
836}
837
838/*******************************************************************************
839**
840** Function         btif_dm_ssp_cfm_req_evt
841**
842** Description      Executes SSP confirm request event in btif context
843**
844** Returns          void
845**
846*******************************************************************************/
847static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ *p_ssp_cfm_req)
848{
849    bt_bdaddr_t bd_addr;
850    bt_bdname_t bd_name;
851    UINT32 cod;
852    BOOLEAN is_incoming = !(pairing_cb.state == BT_BOND_STATE_BONDING);
853
854    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
855
856    /* Remote properties update */
857    btif_update_remote_properties(p_ssp_cfm_req->bd_addr, p_ssp_cfm_req->bd_name,
858                                  p_ssp_cfm_req->dev_class, BT_DEVICE_TYPE_BREDR);
859
860    bdcpy(bd_addr.address, p_ssp_cfm_req->bd_addr);
861    memcpy(bd_name.name, p_ssp_cfm_req->bd_name, BD_NAME_LEN);
862
863    /* Set the pairing_cb based on the local & remote authentication requirements */
864    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
865
866    /* if just_works and bonding bit is not set treat this as temporary */
867    if (p_ssp_cfm_req->just_works && !(p_ssp_cfm_req->loc_auth_req & BTM_AUTH_BONDS) &&
868        !(p_ssp_cfm_req->rmt_auth_req & BTM_AUTH_BONDS) &&
869        !(check_cod((bt_bdaddr_t*)&p_ssp_cfm_req->bd_addr, COD_HID_POINTING)))
870        pairing_cb.is_temp = TRUE;
871    else
872        pairing_cb.is_temp = FALSE;
873
874    pairing_cb.is_ssp = TRUE;
875
876    /* If JustWorks auto-accept */
877    if (p_ssp_cfm_req->just_works)
878    {
879        /* Pairing consent for JustWorks needed if:
880         * 1. Incoming pairing is detected AND
881         * 2. local IO capabilities are DisplayYesNo AND
882         * 3. remote IO capabiltiies are DisplayOnly or NoInputNoOutput;
883         */
884        if ((is_incoming) && ((p_ssp_cfm_req->loc_io_caps == 0x01) &&
885                (p_ssp_cfm_req->rmt_io_caps == 0x00 || p_ssp_cfm_req->rmt_io_caps == 0x03)))
886        {
887            BTIF_TRACE_EVENT("%s: User consent needed for incoming pairing request. loc_io_caps: %d, rmt_io_caps: %d",
888                __FUNCTION__, p_ssp_cfm_req->loc_io_caps, p_ssp_cfm_req->rmt_io_caps);
889        }
890        else
891        {
892            BTIF_TRACE_EVENT("%s: Auto-accept JustWorks pairing", __FUNCTION__);
893            btif_dm_ssp_reply(&bd_addr, BT_SSP_VARIANT_CONSENT, TRUE, 0);
894            return;
895        }
896    }
897
898    cod = devclass2uint(p_ssp_cfm_req->dev_class);
899
900    if ( cod == 0) {
901        ALOGD("cod is 0, set as unclassified");
902        cod = COD_UNCLASSIFIED;
903    }
904
905    pairing_cb.sdp_attempts = 0;
906    HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name, cod,
907                     (p_ssp_cfm_req->just_works ? BT_SSP_VARIANT_CONSENT : BT_SSP_VARIANT_PASSKEY_CONFIRMATION),
908                     p_ssp_cfm_req->num_val);
909}
910
911static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF *p_ssp_key_notif)
912{
913    bt_bdaddr_t bd_addr;
914    bt_bdname_t bd_name;
915    UINT32 cod;
916
917    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
918
919    /* Remote properties update */
920    btif_update_remote_properties(p_ssp_key_notif->bd_addr, p_ssp_key_notif->bd_name,
921                                  p_ssp_key_notif->dev_class, BT_DEVICE_TYPE_BREDR);
922
923    bdcpy(bd_addr.address, p_ssp_key_notif->bd_addr);
924    memcpy(bd_name.name, p_ssp_key_notif->bd_name, BD_NAME_LEN);
925
926    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
927    pairing_cb.is_ssp = TRUE;
928    cod = devclass2uint(p_ssp_key_notif->dev_class);
929
930    if ( cod == 0) {
931        ALOGD("cod is 0, set as unclassified");
932        cod = COD_UNCLASSIFIED;
933    }
934
935    HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name,
936                     cod, BT_SSP_VARIANT_PASSKEY_NOTIFICATION,
937                     p_ssp_key_notif->passkey);
938}
939/*******************************************************************************
940**
941** Function         btif_dm_auth_cmpl_evt
942**
943** Description      Executes authentication complete event in btif context
944**
945** Returns          void
946**
947*******************************************************************************/
948static void btif_dm_auth_cmpl_evt (tBTA_DM_AUTH_CMPL *p_auth_cmpl)
949{
950    /* Save link key, if not temporary */
951    bt_bdaddr_t bd_addr;
952    bt_status_t status = BT_STATUS_FAIL;
953    bt_bond_state_t state = BT_BOND_STATE_NONE;
954    BOOLEAN skip_sdp = FALSE;
955
956    bdcpy(bd_addr.address, p_auth_cmpl->bd_addr);
957    if ( (p_auth_cmpl->success == TRUE) && (p_auth_cmpl->key_present) )
958    {
959        if ((p_auth_cmpl->key_type < HCI_LKEY_TYPE_DEBUG_COMB)  || (p_auth_cmpl->key_type == HCI_LKEY_TYPE_AUTH_COMB) ||
960            (p_auth_cmpl->key_type == HCI_LKEY_TYPE_CHANGED_COMB) || (!pairing_cb.is_temp))
961        {
962            bt_status_t ret;
963            BTIF_TRACE_DEBUG("%s: Storing link key. key_type=0x%x, is_temp=%d",
964                __FUNCTION__, p_auth_cmpl->key_type, pairing_cb.is_temp);
965            ret = btif_storage_add_bonded_device(&bd_addr,
966                                p_auth_cmpl->key, p_auth_cmpl->key_type,
967                                pairing_cb.pin_code_len);
968            ASSERTC(ret == BT_STATUS_SUCCESS, "storing link key failed", ret);
969        }
970        else
971        {
972            BTIF_TRACE_DEBUG("%s: Temporary key. Not storing. key_type=0x%x, is_temp=%d",
973                __FUNCTION__, p_auth_cmpl->key_type, pairing_cb.is_temp);
974            if(pairing_cb.is_temp)
975            {
976                BTIF_TRACE_DEBUG("%s: sending BT_BOND_STATE_NONE for Temp pairing",
977                        __FUNCTION__);
978                bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_NONE);
979                return;
980            }
981        }
982    }
983
984    // Skip SDP for certain  HID Devices
985    if (p_auth_cmpl->success)
986    {
987        status = BT_STATUS_SUCCESS;
988        state = BT_BOND_STATE_BONDED;
989        bdcpy(bd_addr.address, p_auth_cmpl->bd_addr);
990
991        if (check_sdp_bl(&bd_addr) && check_cod_hid(&bd_addr, COD_HID_MAJOR))
992        {
993            ALOGW("%s:skip SDP",
994                              __FUNCTION__);
995            skip_sdp = TRUE;
996        }
997        if(!pairing_cb.is_local_initiated && skip_sdp)
998        {
999            bond_state_changed(status, &bd_addr, state);
1000
1001            ALOGW("%s: Incoming HID Connection",__FUNCTION__);
1002            bt_property_t prop;
1003            bt_bdaddr_t bd_addr;
1004            bt_uuid_t  uuid;
1005            char uuid_str[128] = UUID_HUMAN_INTERFACE_DEVICE;
1006
1007            string_to_uuid(uuid_str, &uuid);
1008
1009            prop.type = BT_PROPERTY_UUIDS;
1010            prop.val = uuid.uu;
1011            prop.len = MAX_UUID_SIZE;
1012
1013            /* Send the event to the BTIF */
1014            HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1015                             BT_STATUS_SUCCESS, &bd_addr, 1, &prop);
1016        }
1017        else
1018        {
1019            /* Trigger SDP on the device */
1020            pairing_cb.sdp_attempts = 1;;
1021
1022            if(btif_dm_inquiry_in_progress)
1023                btif_dm_cancel_discovery();
1024
1025            btif_dm_get_remote_services(&bd_addr);
1026            }
1027            /* Do not call bond_state_changed_cb yet. Wait till fetch remote service is complete */
1028    }
1029    else
1030    {
1031         /*Map the HCI fail reason  to  bt status  */
1032        switch(p_auth_cmpl->fail_reason)
1033        {
1034            case HCI_ERR_PAGE_TIMEOUT:
1035            case HCI_ERR_CONNECTION_TOUT:
1036                status =  BT_STATUS_RMT_DEV_DOWN;
1037                break;
1038
1039            case HCI_ERR_PAIRING_NOT_ALLOWED:
1040                status = BT_STATUS_AUTH_REJECTED;
1041                break;
1042
1043            case HCI_ERR_LMP_RESPONSE_TIMEOUT:
1044                status =  BT_STATUS_AUTH_FAILURE;
1045                break;
1046
1047            /* map the auth failure codes, so we can retry pairing if necessary */
1048            case HCI_ERR_AUTH_FAILURE:
1049            case HCI_ERR_KEY_MISSING:
1050                btif_storage_remove_bonded_device(&bd_addr);
1051            case HCI_ERR_HOST_REJECT_SECURITY:
1052            case HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE:
1053            case HCI_ERR_UNIT_KEY_USED:
1054            case HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED:
1055            case HCI_ERR_INSUFFCIENT_SECURITY:
1056            case HCI_ERR_PEER_USER:
1057            case HCI_ERR_UNSPECIFIED:
1058                BTIF_TRACE_DEBUG(" %s() Authentication fail reason %d",
1059                    __FUNCTION__, p_auth_cmpl->fail_reason);
1060                if (pairing_cb.autopair_attempts  == 1)
1061                {
1062                    BTIF_TRACE_DEBUG("%s(): Adding device to blacklist ", __FUNCTION__);
1063
1064                    /* Add the device to dynamic black list only if this device belongs to Audio/pointing dev class  */
1065                    if (check_cod(&bd_addr, COD_AV_HEADSETS) ||
1066                        check_cod(&bd_addr, COD_AV_HANDSFREE) ||
1067                        check_cod(&bd_addr, COD_AV_HEADPHONES) ||
1068                        check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) ||
1069                        check_cod(&bd_addr, COD_AV_HIFI_AUDIO) ||
1070                        check_cod(&bd_addr, COD_HID_POINTING))
1071                    {
1072                        btif_storage_add_device_to_autopair_blacklist (&bd_addr);
1073                    }
1074                    pairing_cb.autopair_attempts++;
1075
1076                    /* Create the Bond once again */
1077                    BTIF_TRACE_DEBUG("%s() auto pair failed. Reinitiate Bond", __FUNCTION__);
1078                    btif_dm_cb_create_bond (&bd_addr, BTA_TRANSPORT_UNKNOWN);
1079                    return;
1080                }
1081                else
1082                {
1083                    /* if autopair attempts are more than 1, or not attempted */
1084                    status =  BT_STATUS_AUTH_FAILURE;
1085                }
1086                break;
1087
1088            default:
1089                status =  BT_STATUS_FAIL;
1090        }
1091        /* Special Handling for HID Devices */
1092        if (check_cod(&bd_addr, COD_HID_POINTING)) {
1093            /* Remove Device as bonded in nvram as authentication failed */
1094            BTIF_TRACE_DEBUG("%s(): removing hid pointing device from nvram", __FUNCTION__);
1095            btif_storage_remove_bonded_device(&bd_addr);
1096        }
1097        bond_state_changed(status, &bd_addr, state);
1098    }
1099}
1100
1101/******************************************************************************
1102**
1103** Function         btif_dm_search_devices_evt
1104**
1105** Description      Executes search devices callback events in btif context
1106**
1107** Returns          void
1108**
1109******************************************************************************/
1110static void btif_dm_search_devices_evt (UINT16 event, char *p_param)
1111{
1112    tBTA_DM_SEARCH *p_search_data;
1113    BTIF_TRACE_EVENT("%s event=%s", __FUNCTION__, dump_dm_search_event(event));
1114
1115    switch (event)
1116    {
1117        case BTA_DM_DISC_RES_EVT:
1118        {
1119            p_search_data = (tBTA_DM_SEARCH *)p_param;
1120            /* Remote name update */
1121            if (strlen((const char *) p_search_data->disc_res.bd_name))
1122            {
1123                bt_property_t properties[1];
1124                bt_bdaddr_t bdaddr;
1125                bt_status_t status;
1126
1127                properties[0].type = BT_PROPERTY_BDNAME;
1128                properties[0].val = p_search_data->disc_res.bd_name;
1129                properties[0].len = strlen((char *)p_search_data->disc_res.bd_name);
1130                bdcpy(bdaddr.address, p_search_data->disc_res.bd_addr);
1131
1132                status = btif_storage_set_remote_device_property(&bdaddr, &properties[0]);
1133                ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device property", status);
1134                HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1135                                 status, &bdaddr, 1, properties);
1136            }
1137            /* TODO: Services? */
1138        }
1139        break;
1140
1141        case BTA_DM_INQ_RES_EVT:
1142        {
1143            /* inquiry result */
1144            UINT32 cod;
1145            UINT8 *p_eir_remote_name = NULL;
1146            bt_bdname_t bdname;
1147            bt_bdaddr_t bdaddr;
1148            UINT8 remote_name_len;
1149            UINT8 *p_cached_name = NULL;
1150            tBTA_SERVICE_MASK services = 0;
1151            bdstr_t bdstr;
1152
1153            p_search_data = (tBTA_DM_SEARCH *)p_param;
1154            bdcpy(bdaddr.address, p_search_data->inq_res.bd_addr);
1155
1156            BTIF_TRACE_DEBUG("%s() %s device_type = 0x%x\n", __FUNCTION__, bd2str(&bdaddr, &bdstr),
1157#if (BLE_INCLUDED == TRUE)
1158                    p_search_data->inq_res.device_type);
1159#else
1160                    BT_DEVICE_TYPE_BREDR);
1161#endif
1162            bdname.name[0] = 0;
1163
1164            cod = devclass2uint (p_search_data->inq_res.dev_class);
1165
1166            if ( cod == 0) {
1167                ALOGD("cod is 0, set as unclassified");
1168                cod = COD_UNCLASSIFIED;
1169            }
1170
1171            if (!check_eir_remote_name(p_search_data, bdname.name, &remote_name_len))
1172                check_cached_remote_name(p_search_data, bdname.name, &remote_name_len);
1173
1174            /* Check EIR for remote name and services */
1175            if (p_search_data->inq_res.p_eir)
1176            {
1177                BTA_GetEirService(p_search_data->inq_res.p_eir, &services);
1178                BTIF_TRACE_DEBUG("%s()EIR BTA services = %08X", __FUNCTION__, (UINT32)services);
1179                /* TODO:  Get the service list and check to see which uuids we got and send it back to the client. */
1180            }
1181
1182
1183            {
1184                bt_property_t properties[5];
1185                bt_device_type_t dev_type;
1186                UINT8 addr_type;
1187                uint32_t num_properties = 0;
1188                bt_status_t status;
1189
1190                memset(properties, 0, sizeof(properties));
1191                /* BD_ADDR */
1192                BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1193                                    BT_PROPERTY_BDADDR, sizeof(bdaddr), &bdaddr);
1194                num_properties++;
1195                /* BD_NAME */
1196                /* Don't send BDNAME if it is empty */
1197                if (bdname.name[0])
1198                {
1199                    BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1200                                               BT_PROPERTY_BDNAME,
1201                                               strlen((char *)bdname.name), &bdname);
1202                    num_properties++;
1203                }
1204
1205                /* DEV_CLASS */
1206                BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1207                                    BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod);
1208                num_properties++;
1209                /* DEV_TYPE */
1210#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1211                /* FixMe: Assumption is that bluetooth.h and BTE enums match */
1212                dev_type = p_search_data->inq_res.device_type;
1213                addr_type = p_search_data->inq_res.ble_addr_type;
1214#else
1215                dev_type = BT_DEVICE_TYPE_BREDR;
1216#endif
1217                BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1218                                    BT_PROPERTY_TYPE_OF_DEVICE, sizeof(dev_type), &dev_type);
1219                num_properties++;
1220                /* RSSI */
1221                BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties],
1222                                    BT_PROPERTY_REMOTE_RSSI, sizeof(int8_t),
1223                                    &(p_search_data->inq_res.rssi));
1224                num_properties++;
1225
1226                status = btif_storage_add_remote_device(&bdaddr, num_properties, properties);
1227                ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device (inquiry)", status);
1228#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1229                status = btif_storage_set_remote_addr_type(&bdaddr, addr_type);
1230                if (( dev_type == BT_DEVICE_TYPE_DUMO)&&
1231                   (p_search_data->inq_res.flag & BTA_BLE_DMT_CONTROLLER_SPT) &&
1232                   (p_search_data->inq_res.flag & BTA_BLE_DMT_HOST_SPT))
1233                 {
1234                    btif_storage_set_dmt_support_type (&bdaddr, TRUE);
1235                 }
1236                ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote addr type (inquiry)", status);
1237#endif
1238                /* Callback to notify upper layer of device */
1239                HAL_CBACK(bt_hal_cbacks, device_found_cb,
1240                                 num_properties, properties);
1241            }
1242        }
1243        break;
1244
1245        case BTA_DM_INQ_CMPL_EVT:
1246        {
1247#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1248            tBTA_DM_BLE_PF_FILT_PARAMS adv_filt_param;
1249            memset(&adv_filt_param, 0, sizeof(tBTA_DM_BLE_PF_FILT_PARAMS));
1250            BTA_DmBleScanFilterSetup(BTA_DM_BLE_SCAN_COND_DELETE, 0, &adv_filt_param, NULL,
1251                                     bte_scan_filt_param_cfg_evt, 0);
1252#endif
1253        }
1254        break;
1255        case BTA_DM_DISC_CMPL_EVT:
1256        {
1257            HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, BT_DISCOVERY_STOPPED);
1258        }
1259        break;
1260        case BTA_DM_SEARCH_CANCEL_CMPL_EVT:
1261        {
1262           /* if inquiry is not in progress and we get a cancel event, then
1263            * it means we are done with inquiry, but remote_name fetches are in
1264            * progress
1265            *
1266            * if inquiry  is in progress, then we don't want to act on this cancel_cmpl_evt
1267            * but instead wait for the cancel_cmpl_evt via the Busy Level
1268            *
1269            */
1270           if (btif_dm_inquiry_in_progress == FALSE)
1271           {
1272               HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, BT_DISCOVERY_STOPPED);
1273           }
1274        }
1275        break;
1276    }
1277}
1278
1279/*******************************************************************************
1280**
1281** Function         btif_dm_search_services_evt
1282**
1283** Description      Executes search services event in btif context
1284**
1285** Returns          void
1286**
1287*******************************************************************************/
1288static void btif_dm_search_services_evt(UINT16 event, char *p_param)
1289{
1290    tBTA_DM_SEARCH *p_data = (tBTA_DM_SEARCH*)p_param;
1291
1292    BTIF_TRACE_EVENT("%s:  event = %d", __FUNCTION__, event);
1293    switch (event)
1294    {
1295        case BTA_DM_DISC_RES_EVT:
1296        {
1297            bt_uuid_t uuid_arr[BT_MAX_NUM_UUIDS]; /* Max 32 services */
1298            bt_property_t prop;
1299            uint32_t i = 0,  j = 0;
1300            bt_bdaddr_t bd_addr;
1301            bt_status_t ret;
1302
1303            bdcpy(bd_addr.address, p_data->disc_res.bd_addr);
1304
1305            BTIF_TRACE_DEBUG("%s:(result=0x%x, services 0x%x)", __FUNCTION__,
1306                    p_data->disc_res.result, p_data->disc_res.services);
1307            if  ((p_data->disc_res.result != BTA_SUCCESS) &&
1308                 (pairing_cb.state == BT_BOND_STATE_BONDING ) &&
1309                 (pairing_cb.sdp_attempts < BTIF_DM_MAX_SDP_ATTEMPTS_AFTER_PAIRING))
1310            {
1311                BTIF_TRACE_WARNING("%s:SDP failed after bonding re-attempting", __FUNCTION__);
1312                pairing_cb.sdp_attempts++;
1313                btif_dm_get_remote_services(&bd_addr);
1314                return;
1315            }
1316            prop.type = BT_PROPERTY_UUIDS;
1317            prop.len = 0;
1318            if ((p_data->disc_res.result == BTA_SUCCESS) && (p_data->disc_res.num_uuids > 0))
1319            {
1320                 prop.val = p_data->disc_res.p_uuid_list;
1321                 prop.len = p_data->disc_res.num_uuids * MAX_UUID_SIZE;
1322                 for (i=0; i < p_data->disc_res.num_uuids; i++)
1323                 {
1324                      char temp[256];
1325                      uuid_to_string((bt_uuid_t*)(p_data->disc_res.p_uuid_list + (i*MAX_UUID_SIZE)), temp);
1326                      BTIF_TRACE_ERROR("Index: %d uuid:%s", i, temp);
1327                 }
1328            }
1329
1330            /* onUuidChanged requires getBondedDevices to be populated.
1331            ** bond_state_changed needs to be sent prior to remote_device_property
1332            */
1333            if ((pairing_cb.state == BT_BOND_STATE_BONDING) &&
1334                (bdcmp(p_data->disc_res.bd_addr, pairing_cb.bd_addr) == 0)&&
1335                pairing_cb.sdp_attempts > 0)
1336            {
1337                 BTIF_TRACE_DEBUG("%s Remote Service SDP done. Call bond_state_changed_cb BONDED",
1338                                   __FUNCTION__);
1339                 pairing_cb.sdp_attempts  = 0;
1340                 bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDED);
1341            }
1342
1343            if(p_data->disc_res.num_uuids != 0)
1344            {
1345                /* Also write this to the NVRAM */
1346                ret = btif_storage_set_remote_device_property(&bd_addr, &prop);
1347                ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret);
1348                /* Send the event to the BTIF */
1349                HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1350                                 BT_STATUS_SUCCESS, &bd_addr, 1, &prop);
1351            }
1352        }
1353        break;
1354
1355        case BTA_DM_DISC_CMPL_EVT:
1356            /* fixme */
1357        break;
1358
1359#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1360        case BTA_DM_DISC_BLE_RES_EVT:
1361             BTIF_TRACE_DEBUG("%s:, services 0x%x)", __FUNCTION__,
1362                                p_data->disc_ble_res.service.uu.uuid16);
1363             bt_uuid_t  uuid;
1364             int i = 0;
1365             int j = 15;
1366             if (p_data->disc_ble_res.service.uu.uuid16 == UUID_SERVCLASS_LE_HID)
1367             {
1368                BTIF_TRACE_DEBUG("%s: Found HOGP UUID",__FUNCTION__);
1369                bt_property_t prop;
1370                bt_bdaddr_t bd_addr;
1371                char temp[256];
1372                bt_status_t ret;
1373
1374                bta_gatt_convert_uuid16_to_uuid128(uuid.uu,p_data->disc_ble_res.service.uu.uuid16);
1375
1376                while(i < j )
1377                {
1378                    unsigned char c = uuid.uu[j];
1379                    uuid.uu[j] = uuid.uu[i];
1380                    uuid.uu[i] = c;
1381                    i++;
1382                    j--;
1383                }
1384
1385                uuid_to_string(&uuid, temp);
1386                BTIF_TRACE_ERROR(" uuid:%s", temp);
1387
1388                bdcpy(bd_addr.address, p_data->disc_ble_res.bd_addr);
1389                prop.type = BT_PROPERTY_UUIDS;
1390                prop.val = uuid.uu;
1391                prop.len = MAX_UUID_SIZE;
1392
1393                /* Also write this to the NVRAM */
1394                ret = btif_storage_set_remote_device_property(&bd_addr, &prop);
1395                ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret);
1396
1397                /* Send the event to the BTIF */
1398                HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1399                                 BT_STATUS_SUCCESS, &bd_addr, 1, &prop);
1400
1401            }
1402        break;
1403#endif /* BLE_INCLUDED */
1404
1405        default:
1406        {
1407            ASSERTC(0, "unhandled search services event", event);
1408        }
1409        break;
1410    }
1411}
1412
1413/*******************************************************************************
1414**
1415** Function         btif_dm_remote_service_record_evt
1416**
1417** Description      Executes search service record event in btif context
1418**
1419** Returns          void
1420**
1421*******************************************************************************/
1422static void btif_dm_remote_service_record_evt(UINT16 event, char *p_param)
1423{
1424    tBTA_DM_SEARCH *p_data = (tBTA_DM_SEARCH*)p_param;
1425
1426    BTIF_TRACE_EVENT("%s:  event = %d", __FUNCTION__, event);
1427    switch (event)
1428    {
1429        case BTA_DM_DISC_RES_EVT:
1430        {
1431            bt_service_record_t rec;
1432            bt_property_t prop;
1433            uint32_t i = 0;
1434            bt_bdaddr_t bd_addr;
1435
1436            memset(&rec, 0, sizeof(bt_service_record_t));
1437            bdcpy(bd_addr.address, p_data->disc_res.bd_addr);
1438
1439            BTIF_TRACE_DEBUG("%s:(result=0x%x, services 0x%x)", __FUNCTION__,
1440                    p_data->disc_res.result, p_data->disc_res.services);
1441            prop.type = BT_PROPERTY_SERVICE_RECORD;
1442            prop.val = (void*)&rec;
1443            prop.len = sizeof(rec);
1444
1445            /* disc_res.result is overloaded with SCN. Cannot check result */
1446            p_data->disc_res.services &= ~BTA_USER_SERVICE_MASK;
1447            /* TODO: Get the UUID as well */
1448            rec.channel = p_data->disc_res.result - 3;
1449            /* TODO: Need to get the service name using p_raw_data */
1450            rec.name[0] = 0;
1451
1452            HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
1453                             BT_STATUS_SUCCESS, &bd_addr, 1, &prop);
1454        }
1455        break;
1456
1457        default:
1458        {
1459           ASSERTC(0, "unhandled remote service record event", event);
1460        }
1461        break;
1462    }
1463}
1464
1465/*******************************************************************************
1466**
1467** Function         btif_dm_upstreams_cback
1468**
1469** Description      Executes UPSTREAMS events in btif context
1470**
1471** Returns          void
1472**
1473*******************************************************************************/
1474static void btif_dm_upstreams_evt(UINT16 event, char* p_param)
1475{
1476    tBTA_DM_SEC_EVT dm_event = (tBTA_DM_SEC_EVT)event;
1477    tBTA_DM_SEC *p_data = (tBTA_DM_SEC*)p_param;
1478    tBTA_SERVICE_MASK service_mask;
1479    uint32_t i;
1480    bt_bdaddr_t bd_addr;
1481
1482    BTIF_TRACE_EVENT("btif_dm_upstreams_cback  ev: %s", dump_dm_event(event));
1483
1484    switch (event)
1485    {
1486        case BTA_DM_ENABLE_EVT:
1487        {
1488             BD_NAME bdname;
1489             bt_status_t status;
1490             bt_property_t prop;
1491             prop.type = BT_PROPERTY_BDNAME;
1492             prop.len = BD_NAME_LEN;
1493             prop.val = (void*)bdname;
1494
1495             status = btif_storage_get_adapter_property(&prop);
1496             if (status == BT_STATUS_SUCCESS)
1497             {
1498                 /* A name exists in the storage. Make this the device name */
1499                 BTA_DmSetDeviceName((char*)prop.val);
1500             }
1501             else
1502             {
1503                 /* Storage does not have a name yet.
1504                  * Use the default name and write it to the chip
1505                  */
1506                 BTA_DmSetDeviceName(btif_get_default_local_name());
1507             }
1508
1509             /* for each of the enabled services in the mask, trigger the profile
1510              * enable */
1511             service_mask = btif_get_enabled_services_mask();
1512             for (i=0; i <= BTA_MAX_SERVICE_ID; i++)
1513             {
1514                 if (service_mask &
1515                     (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(i)))
1516                 {
1517                     btif_in_execute_service_request(i, TRUE);
1518                 }
1519             }
1520             /* clear control blocks */
1521             memset(&pairing_cb, 0, sizeof(btif_dm_pairing_cb_t));
1522
1523             /* This function will also trigger the adapter_properties_cb
1524             ** and bonded_devices_info_cb
1525             */
1526             btif_storage_load_bonded_devices();
1527
1528             btif_storage_load_autopair_device_list();
1529
1530             btif_enable_bluetooth_evt(p_data->enable.status, p_data->enable.bd_addr);
1531
1532             #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1533             /* Enable local privacy */
1534             /*TODO  Should this call be exposed to JAVA...? */
1535             BTA_DmBleConfigLocalPrivacy(TRUE);
1536             #endif
1537        }
1538        break;
1539
1540        case BTA_DM_DISABLE_EVT:
1541            /* for each of the enabled services in the mask, trigger the profile
1542             * disable */
1543            service_mask = btif_get_enabled_services_mask();
1544            for (i=0; i <= BTA_MAX_SERVICE_ID; i++)
1545            {
1546                if (service_mask &
1547                    (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(i)))
1548                {
1549                    btif_in_execute_service_request(i, FALSE);
1550                }
1551            }
1552            btif_disable_bluetooth_evt();
1553            break;
1554
1555        case BTA_DM_PIN_REQ_EVT:
1556            btif_dm_pin_req_evt(&p_data->pin_req);
1557            break;
1558
1559        case BTA_DM_AUTH_CMPL_EVT:
1560            btif_dm_auth_cmpl_evt(&p_data->auth_cmpl);
1561            break;
1562
1563        case BTA_DM_BOND_CANCEL_CMPL_EVT:
1564            if (pairing_cb.state == BT_BOND_STATE_BONDING)
1565            {
1566                bdcpy(bd_addr.address, pairing_cb.bd_addr);
1567                bond_state_changed(p_data->bond_cancel_cmpl.result, &bd_addr, BT_BOND_STATE_NONE);
1568            }
1569            break;
1570
1571        case BTA_DM_SP_CFM_REQ_EVT:
1572            btif_dm_ssp_cfm_req_evt(&p_data->cfm_req);
1573            break;
1574        case BTA_DM_SP_KEY_NOTIF_EVT:
1575            btif_dm_ssp_key_notif_evt(&p_data->key_notif);
1576            break;
1577
1578        case BTA_DM_DEV_UNPAIRED_EVT:
1579            bdcpy(bd_addr.address, p_data->link_down.bd_addr);
1580
1581            /*special handling for HID devices */
1582            #if (defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE))
1583            btif_hh_remove_device(bd_addr);
1584            #endif
1585            #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1586            btif_storage_remove_ble_bonding_keys(&bd_addr);
1587            #endif
1588            btif_storage_remove_bonded_device(&bd_addr);
1589            bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_NONE);
1590            break;
1591
1592        case BTA_DM_BUSY_LEVEL_EVT:
1593        {
1594
1595            if (p_data->busy_level.level_flags & BTM_BL_INQUIRY_PAGING_MASK)
1596            {
1597                if (p_data->busy_level.level_flags == BTM_BL_INQUIRY_STARTED)
1598                {
1599                       HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb,
1600                                                BT_DISCOVERY_STARTED);
1601                       btif_dm_inquiry_in_progress = TRUE;
1602                }
1603                else if (p_data->busy_level.level_flags == BTM_BL_INQUIRY_CANCELLED)
1604                {
1605                       HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb,
1606                                                BT_DISCOVERY_STOPPED);
1607                       btif_dm_inquiry_in_progress = FALSE;
1608                }
1609                else if (p_data->busy_level.level_flags == BTM_BL_INQUIRY_COMPLETE)
1610                {
1611                       btif_dm_inquiry_in_progress = FALSE;
1612                }
1613            }
1614        }break;
1615
1616        case BTA_DM_LINK_UP_EVT:
1617            bdcpy(bd_addr.address, p_data->link_up.bd_addr);
1618            BTIF_TRACE_DEBUG("BTA_DM_LINK_UP_EVT. Sending BT_ACL_STATE_CONNECTED");
1619
1620            btif_update_remote_version_property(&bd_addr);
1621
1622            HAL_CBACK(bt_hal_cbacks, acl_state_changed_cb, BT_STATUS_SUCCESS,
1623                      &bd_addr, BT_ACL_STATE_CONNECTED);
1624            break;
1625
1626        case BTA_DM_LINK_DOWN_EVT:
1627            bdcpy(bd_addr.address, p_data->link_down.bd_addr);
1628            BTIF_TRACE_DEBUG("BTA_DM_LINK_DOWN_EVT. Sending BT_ACL_STATE_DISCONNECTED");
1629            HAL_CBACK(bt_hal_cbacks, acl_state_changed_cb, BT_STATUS_SUCCESS,
1630                      &bd_addr, BT_ACL_STATE_DISCONNECTED);
1631            break;
1632
1633        case BTA_DM_HW_ERROR_EVT:
1634            BTIF_TRACE_ERROR("Received H/W Error. ");
1635            /* Flush storage data */
1636            btif_config_flush();
1637            usleep(100000); /* 100milliseconds */
1638            /* Killing the process to force a restart as part of fault tolerance */
1639            kill(getpid(), SIGKILL);
1640            break;
1641
1642#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
1643        case BTA_DM_BLE_KEY_EVT:
1644            BTIF_TRACE_DEBUG("BTA_DM_BLE_KEY_EVT key_type=0x%02x ", p_data->ble_key.key_type);
1645
1646            /* If this pairing is by-product of local initiated GATT client Read or Write,
1647            BTA would not have sent BTA_DM_BLE_SEC_REQ_EVT event and Bond state would not
1648            have setup properly. Setup pairing_cb and notify App about Bonding state now*/
1649            if (pairing_cb.state != BT_BOND_STATE_BONDING)
1650            {
1651                BTIF_TRACE_DEBUG("Bond state not sent to App so far.Notify the app now");
1652                bond_state_changed(BT_STATUS_SUCCESS, (bt_bdaddr_t*)p_data->ble_key.bd_addr,
1653                                   BT_BOND_STATE_BONDING);
1654            }
1655            else if (memcmp (pairing_cb.bd_addr, p_data->ble_key.bd_addr, BD_ADDR_LEN)!=0)
1656            {
1657                BTIF_TRACE_ERROR("BD mismatch discard BLE key_type=%d ",p_data->ble_key.key_type);
1658                break;
1659            }
1660
1661            switch (p_data->ble_key.key_type)
1662            {
1663                case BTA_LE_KEY_PENC:
1664                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_PENC");
1665                    pairing_cb.ble.is_penc_key_rcvd = TRUE;
1666                    memcpy(pairing_cb.ble.penc_key.ltk,p_data->ble_key.key_value.penc_key.ltk, 16);
1667                    memcpy(pairing_cb.ble.penc_key.rand, p_data->ble_key.key_value.penc_key.rand,8);
1668                    pairing_cb.ble.penc_key.ediv = p_data->ble_key.key_value.penc_key.ediv;
1669                    pairing_cb.ble.penc_key.sec_level = p_data->ble_key.key_value.penc_key.sec_level;
1670
1671                    for (i=0; i<16; i++)
1672                    {
1673                        BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.ltk[%d]=0x%02x",i,pairing_cb.ble.penc_key.ltk[i]);
1674                    }
1675                    for (i=0; i<8; i++)
1676                    {
1677                        BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.rand[%d]=0x%02x",i,pairing_cb.ble.penc_key.rand[i]);
1678                    }
1679                    BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.ediv=0x%04x",pairing_cb.ble.penc_key.ediv);
1680                    BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.sec_level=0x%02x",pairing_cb.ble.penc_key.sec_level);
1681                    BTIF_TRACE_DEBUG("pairing_cb.ble.penc_key.key_size=0x%02x",pairing_cb.ble.penc_key.key_size);
1682                    break;
1683
1684                case BTA_LE_KEY_PID:
1685                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_PID");
1686                    pairing_cb.ble.is_pid_key_rcvd = TRUE;
1687                    memcpy(pairing_cb.ble.pid_key, p_data->ble_key.key_value.pid_key.irk, 16);
1688                    for (i=0; i<16; i++)
1689                    {
1690                        BTIF_TRACE_DEBUG("pairing_cb.ble.pid_key[%d]=0x%02x",i,pairing_cb.ble.pid_key[i]);
1691                    }
1692                    break;
1693
1694                case BTA_LE_KEY_PCSRK:
1695                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_PCSRK");
1696                    pairing_cb.ble.is_pcsrk_key_rcvd = TRUE;
1697                    pairing_cb.ble.pcsrk_key.counter = p_data->ble_key.key_value.pcsrk_key.counter;
1698                    pairing_cb.ble.pcsrk_key.sec_level = p_data->ble_key.key_value.pcsrk_key.sec_level;
1699                    memcpy(pairing_cb.ble.pcsrk_key.csrk,p_data->ble_key.key_value.pcsrk_key.csrk,16);
1700
1701                    for (i=0; i<16; i++)
1702                    {
1703                        BTIF_TRACE_DEBUG("pairing_cb.ble.pcsrk_key.csrk[%d]=0x%02x",i,pairing_cb.ble.pcsrk_key.csrk[i]);
1704                    }
1705                    BTIF_TRACE_DEBUG("pairing_cb.ble.pcsrk_key.counter=0x%08x",pairing_cb.ble.pcsrk_key.counter);
1706                    BTIF_TRACE_DEBUG("pairing_cb.ble.pcsrk_key.sec_level=0x%02x",pairing_cb.ble.pcsrk_key.sec_level);
1707                    break;
1708
1709                case BTA_LE_KEY_LENC:
1710                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_LENC");
1711                    pairing_cb.ble.is_lenc_key_rcvd = TRUE;
1712                    pairing_cb.ble.lenc_key.div = p_data->ble_key.key_value.lenc_key.div;
1713                    pairing_cb.ble.lenc_key.key_size = p_data->ble_key.key_value.lenc_key.key_size;
1714                    pairing_cb.ble.lenc_key.sec_level = p_data->ble_key.key_value.lenc_key.sec_level;
1715
1716                    BTIF_TRACE_DEBUG("pairing_cb.ble.lenc_key.div=0x%04x",pairing_cb.ble.lenc_key.div);
1717                    BTIF_TRACE_DEBUG("pairing_cb.ble.lenc_key.key_size=0x%02x",pairing_cb.ble.lenc_key.key_size);
1718                    BTIF_TRACE_DEBUG("pairing_cb.ble.lenc_key.sec_level=0x%02x",pairing_cb.ble.lenc_key.sec_level);
1719                    break;
1720
1721
1722
1723                case BTA_LE_KEY_LCSRK:
1724                    BTIF_TRACE_DEBUG("Rcv BTA_LE_KEY_LCSRK");
1725                    pairing_cb.ble.is_lcsrk_key_rcvd = TRUE;
1726                    pairing_cb.ble.lcsrk_key.counter = p_data->ble_key.key_value.lcsrk_key.counter;
1727                    pairing_cb.ble.lcsrk_key.div = p_data->ble_key.key_value.lcsrk_key.div;
1728                    pairing_cb.ble.lcsrk_key.sec_level = p_data->ble_key.key_value.lcsrk_key.sec_level;
1729
1730                    BTIF_TRACE_DEBUG("pairing_cb.ble.lcsrk_key.div=0x%04x",pairing_cb.ble.lcsrk_key.div);
1731                    BTIF_TRACE_DEBUG("pairing_cb.ble.lcsrk_key.counter=0x%08x",pairing_cb.ble.lcsrk_key.counter);
1732                    BTIF_TRACE_DEBUG("pairing_cb.ble.lcsrk_key.sec_level=0x%02x",pairing_cb.ble.lcsrk_key.sec_level);
1733
1734                    break;
1735
1736                default:
1737                    BTIF_TRACE_ERROR("unknown BLE key type (0x%02x)", p_data->ble_key.key_type);
1738                    break;
1739            }
1740
1741            break;
1742        case BTA_DM_BLE_SEC_REQ_EVT:
1743            BTIF_TRACE_DEBUG("BTA_DM_BLE_SEC_REQ_EVT. ");
1744            btif_dm_ble_sec_req_evt(&p_data->ble_req);
1745            break;
1746        case BTA_DM_BLE_PASSKEY_NOTIF_EVT:
1747            BTIF_TRACE_DEBUG("BTA_DM_BLE_PASSKEY_NOTIF_EVT. ");
1748            btif_dm_ble_key_notif_evt(&p_data->key_notif);
1749            break;
1750        case BTA_DM_BLE_PASSKEY_REQ_EVT:
1751            BTIF_TRACE_DEBUG("BTA_DM_BLE_PASSKEY_REQ_EVT. ");
1752            btif_dm_ble_passkey_req_evt(&p_data->pin_req);
1753            break;
1754        case BTA_DM_BLE_OOB_REQ_EVT:
1755            BTIF_TRACE_DEBUG("BTA_DM_BLE_OOB_REQ_EVT. ");
1756            break;
1757        case BTA_DM_BLE_LOCAL_IR_EVT:
1758            BTIF_TRACE_DEBUG("BTA_DM_BLE_LOCAL_IR_EVT. ");
1759            ble_local_key_cb.is_id_keys_rcvd = TRUE;
1760            memcpy(&ble_local_key_cb.id_keys.irk[0], &p_data->ble_id_keys.irk[0], sizeof(BT_OCTET16));
1761            memcpy(&ble_local_key_cb.id_keys.ir[0], &p_data->ble_id_keys.ir[0], sizeof(BT_OCTET16));
1762            memcpy(&ble_local_key_cb.id_keys.dhk[0], &p_data->ble_id_keys.dhk[0], sizeof(BT_OCTET16));
1763            btif_storage_add_ble_local_key( (char *)&ble_local_key_cb.id_keys.irk[0],
1764                                            BTIF_DM_LE_LOCAL_KEY_IR,
1765                                            BT_OCTET16_LEN);
1766            btif_storage_add_ble_local_key( (char *)&ble_local_key_cb.id_keys.ir[0],
1767                                            BTIF_DM_LE_LOCAL_KEY_IRK,
1768                                            BT_OCTET16_LEN);
1769            btif_storage_add_ble_local_key( (char *)&ble_local_key_cb.id_keys.dhk[0],
1770                                            BTIF_DM_LE_LOCAL_KEY_DHK,
1771                                            BT_OCTET16_LEN);
1772            break;
1773        case BTA_DM_BLE_LOCAL_ER_EVT:
1774            BTIF_TRACE_DEBUG("BTA_DM_BLE_LOCAL_ER_EVT. ");
1775            ble_local_key_cb.is_er_rcvd = TRUE;
1776            memcpy(&ble_local_key_cb.er[0], &p_data->ble_er[0], sizeof(BT_OCTET16));
1777            btif_storage_add_ble_local_key( (char *)&ble_local_key_cb.er[0],
1778                                            BTIF_DM_LE_LOCAL_KEY_ER,
1779                                            BT_OCTET16_LEN);
1780            break;
1781
1782        case BTA_DM_BLE_AUTH_CMPL_EVT:
1783            BTIF_TRACE_DEBUG("BTA_DM_BLE_KEY_EVT. ");
1784            btif_dm_ble_auth_cmpl_evt(&p_data->auth_cmpl);
1785            break;
1786
1787        case BTA_DM_LE_FEATURES_READ:
1788        {
1789            tBTM_BLE_VSC_CB cmn_vsc_cb;
1790            bt_local_le_features_t local_le_features;
1791            char buf[512];
1792            bt_property_t prop;
1793            prop.type = BT_PROPERTY_LOCAL_LE_FEATURES;
1794            prop.val = (void*)buf;
1795            prop.len = sizeof(buf);
1796
1797           /* LE features are not stored in storage. Should be retrived from stack */
1798            BTM_BleGetVendorCapabilities(&cmn_vsc_cb);
1799            local_le_features.local_privacy_enabled = BTM_BleLocalPrivacyEnabled();
1800
1801            prop.len = sizeof (bt_local_le_features_t);
1802            if (cmn_vsc_cb.filter_support == 1)
1803                local_le_features.max_adv_filter_supported = cmn_vsc_cb.max_filter;
1804             else
1805                local_le_features.max_adv_filter_supported = 0;
1806            local_le_features.max_adv_instance = cmn_vsc_cb.adv_inst_max;
1807            local_le_features.max_irk_list_size = cmn_vsc_cb.max_irk_list_sz;
1808            local_le_features.rpa_offload_supported = cmn_vsc_cb.rpa_offloading;
1809            local_le_features.scan_result_storage_size_hibyte =
1810                (cmn_vsc_cb.tot_scan_results_strg >> 8) & (0xFF);
1811            local_le_features.scan_result_storage_size_lobyte =
1812                (cmn_vsc_cb.tot_scan_results_strg) & (0xFF);
1813            local_le_features.activity_energy_info_supported = cmn_vsc_cb.energy_support;
1814            memcpy(prop.val, &local_le_features, prop.len);
1815            HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, BT_STATUS_SUCCESS, 1, &prop);
1816            break;
1817         }
1818
1819        case BTA_DM_ENER_INFO_READ:
1820        {
1821            btif_activity_energy_info_cb_t *p_ener_data = (btif_activity_energy_info_cb_t*) p_param;
1822            bt_activity_energy_info energy_info;
1823            energy_info.status = p_ener_data->status;
1824            energy_info.ctrl_state = p_ener_data->ctrl_state;
1825            energy_info.rx_time = p_ener_data->rx_time;
1826            energy_info.tx_time = p_ener_data->tx_time;
1827            energy_info.idle_time = p_ener_data->idle_time;
1828            energy_info.energy_used = p_ener_data->energy_used;
1829            HAL_CBACK(bt_hal_cbacks, energy_info_cb, &energy_info);
1830            break;
1831        }
1832#endif
1833
1834        case BTA_DM_AUTHORIZE_EVT:
1835        case BTA_DM_SIG_STRENGTH_EVT:
1836        case BTA_DM_SP_RMT_OOB_EVT:
1837        case BTA_DM_SP_KEYPRESS_EVT:
1838        case BTA_DM_ROLE_CHG_EVT:
1839
1840        default:
1841            BTIF_TRACE_WARNING( "btif_dm_cback : unhandled event (%d)", event );
1842            break;
1843    }
1844} /* btui_security_cback() */
1845
1846
1847/*******************************************************************************
1848**
1849** Function         btif_dm_generic_evt
1850**
1851** Description      Executes non-BTA upstream events in BTIF context
1852**
1853** Returns          void
1854**
1855*******************************************************************************/
1856static void btif_dm_generic_evt(UINT16 event, char* p_param)
1857{
1858    BTIF_TRACE_EVENT("%s: event=%d", __FUNCTION__, event);
1859    switch(event)
1860    {
1861        case BTIF_DM_CB_DISCOVERY_STARTED:
1862        {
1863            HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, BT_DISCOVERY_STARTED);
1864        }
1865        break;
1866
1867        case BTIF_DM_CB_CREATE_BOND:
1868        {
1869            btif_dm_create_bond_cb_t *create_bond_cb = (btif_dm_create_bond_cb_t*)p_param;
1870            btif_dm_cb_create_bond(&create_bond_cb->bdaddr, create_bond_cb->transport);
1871        }
1872        break;
1873
1874        case BTIF_DM_CB_REMOVE_BOND:
1875        {
1876            btif_dm_cb_remove_bond((bt_bdaddr_t *)p_param);
1877        }
1878        break;
1879
1880        case BTIF_DM_CB_HID_REMOTE_NAME:
1881        {
1882            btif_dm_cb_hid_remote_name((tBTM_REMOTE_DEV_NAME *)p_param);
1883        }
1884        break;
1885
1886        case BTIF_DM_CB_BOND_STATE_BONDING:
1887            {
1888                bond_state_changed(BT_STATUS_SUCCESS, (bt_bdaddr_t *)p_param, BT_BOND_STATE_BONDING);
1889            }
1890            break;
1891        case BTIF_DM_CB_LE_TX_TEST:
1892        case BTIF_DM_CB_LE_RX_TEST:
1893            {
1894                uint8_t status;
1895                STREAM_TO_UINT8(status, p_param);
1896                HAL_CBACK(bt_hal_cbacks, le_test_mode_cb,
1897                      (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, 0);
1898            }
1899            break;
1900        case BTIF_DM_CB_LE_TEST_END:
1901            {
1902                uint8_t status;
1903                uint16_t count = 0;
1904                STREAM_TO_UINT8(status, p_param);
1905                if (status == 0)
1906                    STREAM_TO_UINT16(count, p_param);
1907                HAL_CBACK(bt_hal_cbacks, le_test_mode_cb,
1908                      (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, count);
1909            }
1910            break;
1911        default:
1912        {
1913            BTIF_TRACE_WARNING("%s : Unknown event 0x%x", __FUNCTION__, event);
1914        }
1915        break;
1916    }
1917}
1918
1919/*******************************************************************************
1920**
1921** Function         bte_dm_evt
1922**
1923** Description      Switches context from BTE to BTIF for all DM events
1924**
1925** Returns          void
1926**
1927*******************************************************************************/
1928
1929void bte_dm_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC *p_data)
1930{
1931    bt_status_t status;
1932
1933    /* switch context to btif task context (copy full union size for convenience) */
1934    status = btif_transfer_context(btif_dm_upstreams_evt, (uint16_t)event, (void*)p_data, sizeof(tBTA_DM_SEC), NULL);
1935
1936    /* catch any failed context transfers */
1937    ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status);
1938}
1939
1940/*******************************************************************************
1941**
1942** Function         bte_search_devices_evt
1943**
1944** Description      Switches context from BTE to BTIF for DM search events
1945**
1946** Returns          void
1947**
1948*******************************************************************************/
1949static void bte_search_devices_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH *p_data)
1950{
1951    UINT16 param_len = 0;
1952
1953    if (p_data)
1954        param_len += sizeof(tBTA_DM_SEARCH);
1955    /* Allocate buffer to hold the pointers (deep copy). The pointers will point to the end of the tBTA_DM_SEARCH */
1956    switch (event)
1957    {
1958        case BTA_DM_INQ_RES_EVT:
1959        {
1960            if (p_data->inq_res.p_eir)
1961                param_len += HCI_EXT_INQ_RESPONSE_LEN;
1962        }
1963        break;
1964
1965        case BTA_DM_DISC_RES_EVT:
1966        {
1967            if (p_data->disc_res.raw_data_size && p_data->disc_res.p_raw_data)
1968                param_len += p_data->disc_res.raw_data_size;
1969        }
1970        break;
1971    }
1972    BTIF_TRACE_DEBUG("%s event=%s param_len=%d", __FUNCTION__, dump_dm_search_event(event), param_len);
1973
1974    /* if remote name is available in EIR, set teh flag so that stack doesnt trigger RNR */
1975    if (event == BTA_DM_INQ_RES_EVT)
1976        p_data->inq_res.remt_name_not_required = check_eir_remote_name(p_data, NULL, NULL);
1977
1978    btif_transfer_context (btif_dm_search_devices_evt , (UINT16) event, (void *)p_data, param_len,
1979        (param_len > sizeof(tBTA_DM_SEARCH)) ? search_devices_copy_cb : NULL);
1980}
1981
1982/*******************************************************************************
1983**
1984** Function         bte_dm_search_services_evt
1985**
1986** Description      Switches context from BTE to BTIF for DM search services
1987**                  event
1988**
1989** Returns          void
1990**
1991*******************************************************************************/
1992static void bte_dm_search_services_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH *p_data)
1993{
1994    UINT16 param_len = 0;
1995   if (p_data)
1996       param_len += sizeof(tBTA_DM_SEARCH);
1997   switch (event)
1998   {
1999         case BTA_DM_DISC_RES_EVT:
2000         {
2001             if ((p_data->disc_res.result == BTA_SUCCESS) && (p_data->disc_res.num_uuids > 0)) {
2002                  param_len += (p_data->disc_res.num_uuids * MAX_UUID_SIZE);
2003             }
2004         } break;
2005   }
2006   /* TODO: The only other member that needs a deep copy is the p_raw_data. But not sure
2007    * if raw_data is needed. */
2008   btif_transfer_context(btif_dm_search_services_evt, event, (char*)p_data, param_len,
2009         (param_len > sizeof(tBTA_DM_SEARCH)) ? search_services_copy_cb : NULL);
2010}
2011
2012/*******************************************************************************
2013**
2014** Function         bte_dm_remote_service_record_evt
2015**
2016** Description      Switches context from BTE to BTIF for DM search service
2017**                  record event
2018**
2019** Returns          void
2020**
2021*******************************************************************************/
2022static void bte_dm_remote_service_record_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH *p_data)
2023{
2024   /* TODO: The only member that needs a deep copy is the p_raw_data. But not sure yet if this is needed. */
2025   btif_transfer_context(btif_dm_remote_service_record_evt, event, (char*)p_data, sizeof(tBTA_DM_SEARCH), NULL);
2026}
2027
2028#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2029/*******************************************************************************
2030**
2031** Function         bta_energy_info_cb
2032**
2033** Description      Switches context from BTE to BTIF for DM energy info event
2034**
2035** Returns          void
2036**
2037*******************************************************************************/
2038static void bta_energy_info_cb(tBTA_DM_BLE_TX_TIME_MS tx_time, tBTA_DM_BLE_RX_TIME_MS rx_time,
2039                                    tBTA_DM_BLE_IDLE_TIME_MS idle_time,
2040                                    tBTA_DM_BLE_ENERGY_USED energy_used,
2041                                    tBTA_DM_CONTRL_STATE ctrl_state, tBTA_STATUS status)
2042{
2043    BTIF_TRACE_DEBUG("energy_info_cb-Status:%d,state=%d,tx_t=%ld, rx_t=%ld, idle_time=%ld,used=%ld",
2044        status, ctrl_state, tx_time, rx_time, idle_time, energy_used);
2045
2046    btif_activity_energy_info_cb_t btif_cb;
2047    btif_cb.status = status;
2048    btif_cb.ctrl_state = ctrl_state;
2049    btif_cb.tx_time = (uint64_t) tx_time;
2050    btif_cb.rx_time = (uint64_t) rx_time;
2051    btif_cb.idle_time =(uint64_t) idle_time;
2052    btif_cb.energy_used =(uint64_t) energy_used;
2053    btif_transfer_context(btif_dm_upstreams_evt, BTA_DM_ENER_INFO_READ,
2054                          (char*) &btif_cb, sizeof(btif_activity_energy_info_cb_t), NULL);
2055}
2056#endif
2057
2058/*******************************************************************************
2059**
2060** Function         bte_scan_filt_param_cfg_evt
2061**
2062** Description      Scan filter param config event
2063**
2064** Returns          void
2065**
2066*******************************************************************************/
2067static void bte_scan_filt_param_cfg_evt(UINT8 action_type,
2068                                        tBTA_DM_BLE_PF_AVBL_SPACE avbl_space,
2069                                        tBTA_DM_BLE_REF_VALUE ref_value, tBTA_STATUS status)
2070{
2071    /* This event occurs on calling BTA_DmBleCfgFilterCondition internally,
2072    ** and that is why there is no HAL callback
2073    */
2074    if(BTA_SUCCESS != status)
2075    {
2076        BTIF_TRACE_ERROR("%s, %d", __FUNCTION__, status);
2077    }
2078    else
2079    {
2080        BTIF_TRACE_DEBUG("%s", __FUNCTION__);
2081    }
2082}
2083
2084/*****************************************************************************
2085**
2086**   btif api functions (no context switch)
2087**
2088*****************************************************************************/
2089
2090/*******************************************************************************
2091**
2092** Function         btif_dm_start_discovery
2093**
2094** Description      Start device discovery/inquiry
2095**
2096** Returns          bt_status_t
2097**
2098*******************************************************************************/
2099bt_status_t btif_dm_start_discovery(void)
2100{
2101    tBTA_DM_INQ inq_params;
2102    tBTA_SERVICE_MASK services = 0;
2103    tBTA_DM_BLE_PF_FILT_PARAMS adv_filt_param;
2104
2105    BTIF_TRACE_EVENT("%s", __FUNCTION__);
2106
2107#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2108    memset(&adv_filt_param, 0, sizeof(tBTA_DM_BLE_PF_FILT_PARAMS));
2109    /* Cleanup anything remaining on index 0 */
2110    BTA_DmBleScanFilterSetup(BTA_DM_BLE_SCAN_COND_DELETE, 0, &adv_filt_param, NULL,
2111                             bte_scan_filt_param_cfg_evt, 0);
2112
2113    /* Add an allow-all filter on index 0*/
2114    adv_filt_param.dely_mode = IMMEDIATE_DELY_MODE;
2115    adv_filt_param.feat_seln = ALLOW_ALL_FILTER;
2116    adv_filt_param.filt_logic_type = BTA_DM_BLE_PF_FILT_LOGIC_OR;
2117    adv_filt_param.list_logic_type = BTA_DM_BLE_PF_LIST_LOGIC_OR;
2118    adv_filt_param.rssi_low_thres = LOWEST_RSSI_VALUE;
2119    adv_filt_param.rssi_high_thres = LOWEST_RSSI_VALUE;
2120    BTA_DmBleScanFilterSetup(BTA_DM_BLE_SCAN_COND_ADD, 0, &adv_filt_param, NULL,
2121                             bte_scan_filt_param_cfg_evt, 0);
2122
2123    /* TODO: Do we need to handle multiple inquiries at the same time? */
2124
2125    /* Set inquiry params and call API */
2126    inq_params.mode = BTA_DM_GENERAL_INQUIRY|BTA_BLE_GENERAL_INQUIRY;
2127#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE)
2128    inq_params.intl_duration[0]= BTIF_DM_INTERLEAVE_DURATION_BR_ONE;
2129    inq_params.intl_duration[1]= BTIF_DM_INTERLEAVE_DURATION_LE_ONE;
2130    inq_params.intl_duration[2]= BTIF_DM_INTERLEAVE_DURATION_BR_TWO;
2131    inq_params.intl_duration[3]= BTIF_DM_INTERLEAVE_DURATION_LE_TWO;
2132#endif
2133#else
2134    inq_params.mode = BTA_DM_GENERAL_INQUIRY;
2135#endif
2136    inq_params.duration = BTIF_DM_DEFAULT_INQ_MAX_DURATION;
2137
2138    inq_params.max_resps = BTIF_DM_DEFAULT_INQ_MAX_RESULTS;
2139    inq_params.report_dup = TRUE;
2140
2141    inq_params.filter_type = BTA_DM_INQ_CLR;
2142    /* TODO: Filter device by BDA needs to be implemented here */
2143
2144    /* Will be enabled to TRUE once inquiry busy level has been received */
2145    btif_dm_inquiry_in_progress = FALSE;
2146    /* find nearby devices */
2147    BTA_DmSearch(&inq_params, services, bte_search_devices_evt);
2148
2149    return BT_STATUS_SUCCESS;
2150}
2151
2152/*******************************************************************************
2153**
2154** Function         btif_dm_cancel_discovery
2155**
2156** Description      Cancels search
2157**
2158** Returns          bt_status_t
2159**
2160*******************************************************************************/
2161bt_status_t btif_dm_cancel_discovery(void)
2162{
2163    BTIF_TRACE_EVENT("%s", __FUNCTION__);
2164    BTA_DmSearchCancel();
2165    return BT_STATUS_SUCCESS;
2166}
2167
2168/*******************************************************************************
2169**
2170** Function         btif_dm_create_bond
2171**
2172** Description      Initiate bonding with the specified device
2173**
2174** Returns          bt_status_t
2175**
2176*******************************************************************************/
2177bt_status_t btif_dm_create_bond(const bt_bdaddr_t *bd_addr, int transport)
2178{
2179    btif_dm_create_bond_cb_t create_bond_cb;
2180    create_bond_cb.transport = transport;
2181    bdcpy(create_bond_cb.bdaddr.address, bd_addr->address);
2182
2183    bdstr_t bdstr;
2184    BTIF_TRACE_EVENT("%s: bd_addr=%s, transport=%d", __FUNCTION__,
2185            bd2str((bt_bdaddr_t *) bd_addr, &bdstr), transport);
2186    if (pairing_cb.state != BT_BOND_STATE_NONE)
2187        return BT_STATUS_BUSY;
2188
2189    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_CREATE_BOND,
2190                          (char *)&create_bond_cb, sizeof(btif_dm_create_bond_cb_t), NULL);
2191
2192    return BT_STATUS_SUCCESS;
2193}
2194
2195/*******************************************************************************
2196**
2197** Function         btif_dm_cancel_bond
2198**
2199** Description      Initiate bonding with the specified device
2200**
2201** Returns          bt_status_t
2202**
2203*******************************************************************************/
2204
2205bt_status_t btif_dm_cancel_bond(const bt_bdaddr_t *bd_addr)
2206{
2207    bdstr_t bdstr;
2208
2209    BTIF_TRACE_EVENT("%s: bd_addr=%s", __FUNCTION__, bd2str((bt_bdaddr_t *)bd_addr, &bdstr));
2210
2211    /* TODO:
2212    **  1. Restore scan modes
2213    **  2. special handling for HID devices
2214    */
2215    if (pairing_cb.state == BT_BOND_STATE_BONDING)
2216    {
2217
2218#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2219
2220        if (pairing_cb.is_ssp)
2221        {
2222            if (pairing_cb.is_le_only)
2223            {
2224                BTA_DmBleSecurityGrant((UINT8 *)bd_addr->address,BTA_DM_SEC_PAIR_NOT_SPT);
2225            }
2226            else
2227            {
2228                BTA_DmConfirm( (UINT8 *)bd_addr->address, FALSE);
2229                BTA_DmBondCancel ((UINT8 *)bd_addr->address);
2230                btif_storage_remove_bonded_device((bt_bdaddr_t *)bd_addr);
2231            }
2232        }
2233        else
2234        {
2235            if (pairing_cb.is_le_only)
2236            {
2237                BTA_DmBondCancel ((UINT8 *)bd_addr->address);
2238            }
2239            else
2240            {
2241                BTA_DmPinReply( (UINT8 *)bd_addr->address, FALSE, 0, NULL);
2242            }
2243        /* Cancel bonding, in case it is in ACL connection setup state */
2244        BTA_DmBondCancel ((UINT8 *)bd_addr->address);
2245        }
2246
2247#else
2248        if (pairing_cb.is_ssp)
2249        {
2250            BTA_DmConfirm( (UINT8 *)bd_addr->address, FALSE);
2251        }
2252        else
2253        {
2254            BTA_DmPinReply( (UINT8 *)bd_addr->address, FALSE, 0, NULL);
2255        }
2256        /* Cancel bonding, in case it is in ACL connection setup state */
2257        BTA_DmBondCancel ((UINT8 *)bd_addr->address);
2258        btif_storage_remove_bonded_device((bt_bdaddr_t *)bd_addr);
2259#endif
2260    }
2261
2262    return BT_STATUS_SUCCESS;
2263}
2264
2265/*******************************************************************************
2266**
2267** Function         btif_dm_hh_open_failed
2268**
2269** Description      informs the upper layers if the HH have failed during bonding
2270**
2271** Returns          none
2272**
2273*******************************************************************************/
2274
2275void btif_dm_hh_open_failed(bt_bdaddr_t *bdaddr)
2276{
2277    if (pairing_cb.state == BT_BOND_STATE_BONDING &&
2278            bdcmp(bdaddr->address, pairing_cb.bd_addr) == 0)
2279    {
2280        bond_state_changed(BT_STATUS_FAIL, bdaddr, BT_BOND_STATE_NONE);
2281    }
2282}
2283
2284/*******************************************************************************
2285**
2286** Function         btif_dm_remove_bond
2287**
2288** Description      Removes bonding with the specified device
2289**
2290** Returns          bt_status_t
2291**
2292*******************************************************************************/
2293
2294bt_status_t btif_dm_remove_bond(const bt_bdaddr_t *bd_addr)
2295{
2296    bdstr_t bdstr;
2297
2298    BTIF_TRACE_EVENT("%s: bd_addr=%s", __FUNCTION__, bd2str((bt_bdaddr_t *)bd_addr, &bdstr));
2299    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_REMOVE_BOND,
2300                          (char *)bd_addr, sizeof(bt_bdaddr_t), NULL);
2301
2302    return BT_STATUS_SUCCESS;
2303}
2304
2305/*******************************************************************************
2306**
2307** Function         btif_dm_pin_reply
2308**
2309** Description      BT legacy pairing - PIN code reply
2310**
2311** Returns          bt_status_t
2312**
2313*******************************************************************************/
2314
2315bt_status_t btif_dm_pin_reply( const bt_bdaddr_t *bd_addr, uint8_t accept,
2316                               uint8_t pin_len, bt_pin_code_t *pin_code)
2317{
2318    BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept);
2319    if (pin_code == NULL)
2320        return BT_STATUS_FAIL;
2321#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2322
2323    if (pairing_cb.is_le_only)
2324    {
2325        int i;
2326        UINT32 passkey = 0;
2327        int multi[] = {100000, 10000, 1000, 100, 10,1};
2328        BD_ADDR remote_bd_addr;
2329        bdcpy(remote_bd_addr, bd_addr->address);
2330        for (i = 0; i < 6; i++)
2331        {
2332            passkey += (multi[i] * (pin_code->pin[i] - '0'));
2333        }
2334        BTIF_TRACE_DEBUG("btif_dm_pin_reply: passkey: %d", passkey);
2335        BTA_DmBlePasskeyReply(remote_bd_addr, accept, passkey);
2336
2337    }
2338    else
2339    {
2340        BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
2341        if (accept)
2342            pairing_cb.pin_code_len = pin_len;
2343    }
2344#else
2345    BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
2346
2347    if (accept)
2348        pairing_cb.pin_code_len = pin_len;
2349#endif
2350    return BT_STATUS_SUCCESS;
2351}
2352
2353/*******************************************************************************
2354**
2355** Function         btif_dm_ssp_reply
2356**
2357** Description      BT SSP Reply - Just Works, Numeric Comparison & Passkey Entry
2358**
2359** Returns          bt_status_t
2360**
2361*******************************************************************************/
2362bt_status_t btif_dm_ssp_reply(const bt_bdaddr_t *bd_addr,
2363                                 bt_ssp_variant_t variant, uint8_t accept,
2364                                 uint32_t passkey)
2365{
2366    UNUSED(passkey);
2367
2368    if (variant == BT_SSP_VARIANT_PASSKEY_ENTRY)
2369    {
2370        /* This is not implemented in the stack.
2371         * For devices with display, this is not needed
2372        */
2373        BTIF_TRACE_WARNING("%s: Not implemented", __FUNCTION__);
2374        return BT_STATUS_FAIL;
2375    }
2376    /* BT_SSP_VARIANT_CONSENT & BT_SSP_VARIANT_PASSKEY_CONFIRMATION supported */
2377    BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept);
2378#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2379    if (pairing_cb.is_le_only)
2380    {
2381        if (accept)
2382            BTA_DmBleSecurityGrant((UINT8 *)bd_addr->address,BTA_DM_SEC_GRANTED);
2383        else
2384            BTA_DmBleSecurityGrant((UINT8 *)bd_addr->address,BTA_DM_SEC_PAIR_NOT_SPT);
2385    }
2386    else
2387        BTA_DmConfirm( (UINT8 *)bd_addr->address, accept);
2388
2389#else
2390    BTA_DmConfirm( (UINT8 *)bd_addr->address, accept);
2391#endif
2392    return BT_STATUS_SUCCESS;
2393}
2394
2395/*******************************************************************************
2396**
2397** Function         btif_dm_get_adapter_property
2398**
2399** Description     Queries the BTA for the adapter property
2400**
2401** Returns          bt_status_t
2402**
2403*******************************************************************************/
2404bt_status_t btif_dm_get_adapter_property(bt_property_t *prop)
2405{
2406    bt_status_t status;
2407
2408    BTIF_TRACE_EVENT("%s: type=0x%x", __FUNCTION__, prop->type);
2409    switch (prop->type)
2410    {
2411        case BT_PROPERTY_BDNAME:
2412        {
2413            bt_bdname_t *bd_name = (bt_bdname_t*)prop->val;
2414            strcpy((char *)bd_name->name, btif_get_default_local_name());
2415            prop->len = strlen((char *)bd_name->name);
2416        }
2417        break;
2418
2419        case BT_PROPERTY_ADAPTER_SCAN_MODE:
2420        {
2421            /* if the storage does not have it. Most likely app never set it. Default is NONE */
2422            bt_scan_mode_t *mode = (bt_scan_mode_t*)prop->val;
2423            *mode = BT_SCAN_MODE_NONE;
2424            prop->len = sizeof(bt_scan_mode_t);
2425        }
2426        break;
2427
2428        case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
2429        {
2430            uint32_t *tmt = (uint32_t*)prop->val;
2431            *tmt = 120; /* default to 120s, if not found in NV */
2432            prop->len = sizeof(uint32_t);
2433        }
2434        break;
2435
2436        default:
2437            prop->len = 0;
2438            return BT_STATUS_FAIL;
2439    }
2440    return BT_STATUS_SUCCESS;
2441}
2442
2443/*******************************************************************************
2444**
2445** Function         btif_dm_get_remote_services
2446**
2447** Description      Start SDP to get remote services
2448**
2449** Returns          bt_status_t
2450**
2451*******************************************************************************/
2452bt_status_t btif_dm_get_remote_services(bt_bdaddr_t *remote_addr)
2453{
2454    bdstr_t bdstr;
2455
2456    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bd2str(remote_addr, &bdstr));
2457
2458    BTA_DmDiscover(remote_addr->address, BTA_ALL_SERVICE_MASK,
2459                   bte_dm_search_services_evt, TRUE);
2460
2461    return BT_STATUS_SUCCESS;
2462}
2463
2464/*******************************************************************************
2465**
2466** Function         btif_dm_get_remote_service_record
2467**
2468** Description      Start SDP to get remote service record
2469**
2470**
2471** Returns          bt_status_t
2472*******************************************************************************/
2473bt_status_t btif_dm_get_remote_service_record(bt_bdaddr_t *remote_addr,
2474                                                    bt_uuid_t *uuid)
2475{
2476    tSDP_UUID sdp_uuid;
2477    bdstr_t bdstr;
2478
2479    BTIF_TRACE_EVENT("%s: remote_addr=%s", __FUNCTION__, bd2str(remote_addr, &bdstr));
2480
2481    sdp_uuid.len = MAX_UUID_SIZE;
2482    memcpy(sdp_uuid.uu.uuid128, uuid->uu, MAX_UUID_SIZE);
2483
2484    BTA_DmDiscoverUUID(remote_addr->address, &sdp_uuid,
2485                       bte_dm_remote_service_record_evt, TRUE);
2486
2487    return BT_STATUS_SUCCESS;
2488}
2489
2490void btif_dm_execute_service_request(UINT16 event, char *p_param)
2491{
2492    BOOLEAN b_enable = FALSE;
2493    bt_status_t status;
2494    if (event == BTIF_DM_ENABLE_SERVICE)
2495    {
2496        b_enable = TRUE;
2497    }
2498    status = btif_in_execute_service_request(*((tBTA_SERVICE_ID*)p_param), b_enable);
2499    if (status == BT_STATUS_SUCCESS)
2500    {
2501        bt_property_t property;
2502        bt_uuid_t local_uuids[BT_MAX_NUM_UUIDS];
2503
2504        /* Now send the UUID_PROPERTY_CHANGED event to the upper layer */
2505        BTIF_STORAGE_FILL_PROPERTY(&property, BT_PROPERTY_UUIDS,
2506                                    sizeof(local_uuids), local_uuids);
2507        btif_storage_get_adapter_property(&property);
2508        HAL_CBACK(bt_hal_cbacks, adapter_properties_cb,
2509                          BT_STATUS_SUCCESS, 1, &property);
2510    }
2511    return;
2512}
2513
2514void btif_dm_proc_io_req(BD_ADDR bd_addr, tBTA_IO_CAP *p_io_cap, tBTA_OOB_DATA *p_oob_data,
2515                      tBTA_AUTH_REQ *p_auth_req, BOOLEAN is_orig)
2516{
2517    UINT8   yes_no_bit = BTA_AUTH_SP_YES & *p_auth_req;
2518    /* if local initiated:
2519    **      1. set DD + MITM
2520    ** if remote initiated:
2521    **      1. Copy over the auth_req from peer's io_rsp
2522    **      2. Set the MITM if peer has it set or if peer has DisplayYesNo (iPhone)
2523    ** as a fallback set MITM+GB if peer had MITM set
2524    */
2525    UNUSED (bd_addr);
2526    UNUSED (p_io_cap);
2527    UNUSED (p_oob_data);
2528
2529
2530    BTIF_TRACE_DEBUG("+%s: p_auth_req=%d", __FUNCTION__, *p_auth_req);
2531    if(pairing_cb.is_local_initiated)
2532    {
2533        /* if initing/responding to a dedicated bonding, use dedicate bonding bit */
2534        *p_auth_req = BTA_AUTH_DD_BOND | BTA_AUTH_SP_YES;
2535    }
2536    else if (!is_orig)
2537    {
2538        /* peer initiated paring. They probably know what they want.
2539        ** Copy the mitm from peer device.
2540        */
2541        BTIF_TRACE_DEBUG("%s: setting p_auth_req to peer's: %d",
2542                __FUNCTION__, pairing_cb.auth_req);
2543        *p_auth_req = (pairing_cb.auth_req & BTA_AUTH_BONDS);
2544
2545        /* copy over the MITM bit as well. In addition if the peer has DisplayYesNo, force MITM */
2546        if ((yes_no_bit) || (pairing_cb.io_cap & BTM_IO_CAP_IO) )
2547            *p_auth_req |= BTA_AUTH_SP_YES;
2548    }
2549    else if (yes_no_bit)
2550    {
2551        /* set the general bonding bit for stored device */
2552        *p_auth_req = BTA_AUTH_GEN_BOND | yes_no_bit;
2553    }
2554    BTIF_TRACE_DEBUG("-%s: p_auth_req=%d", __FUNCTION__, *p_auth_req);
2555}
2556
2557void btif_dm_proc_io_rsp(BD_ADDR bd_addr, tBTA_IO_CAP io_cap,
2558                      tBTA_OOB_DATA oob_data, tBTA_AUTH_REQ auth_req)
2559{
2560    UNUSED (bd_addr);
2561    UNUSED (oob_data);
2562
2563    if(auth_req & BTA_AUTH_BONDS)
2564    {
2565        BTIF_TRACE_DEBUG("%s auth_req:%d", __FUNCTION__, auth_req);
2566        pairing_cb.auth_req = auth_req;
2567        pairing_cb.io_cap = io_cap;
2568    }
2569}
2570
2571#if (BTM_OOB_INCLUDED == TRUE)
2572void btif_dm_set_oob_for_io_req(tBTA_OOB_DATA  *p_oob_data)
2573{
2574    if (oob_cb.sp_c[0] == 0 && oob_cb.sp_c[1] == 0 &&
2575        oob_cb.sp_c[2] == 0 && oob_cb.sp_c[3] == 0 )
2576    {
2577        *p_oob_data = FALSE;
2578    }
2579    else
2580    {
2581        *p_oob_data = TRUE;
2582    }
2583    BTIF_TRACE_DEBUG("btif_dm_set_oob_for_io_req *p_oob_data=%d", *p_oob_data);
2584}
2585#endif /* BTM_OOB_INCLUDED */
2586
2587#ifdef BTIF_DM_OOB_TEST
2588void btif_dm_load_local_oob(void)
2589{
2590    char prop_oob[PROPERTY_VALUE_MAX];
2591    property_get("service.brcm.bt.oob", prop_oob, "3");
2592    BTIF_TRACE_DEBUG("btif_dm_load_local_oob prop_oob = %s",prop_oob);
2593    if (prop_oob[0] != '3')
2594    {
2595#if (BTM_OOB_INCLUDED == TRUE)
2596        if (oob_cb.sp_c[0] == 0 && oob_cb.sp_c[1] == 0 &&
2597            oob_cb.sp_c[2] == 0 && oob_cb.sp_c[3] == 0 )
2598        {
2599            BTIF_TRACE_DEBUG("btif_dm_load_local_oob: read OOB, call BTA_DmLocalOob()");
2600            BTA_DmLocalOob();
2601        }
2602#else
2603        BTIF_TRACE_ERROR("BTM_OOB_INCLUDED is FALSE!!(btif_dm_load_local_oob)");
2604#endif
2605    }
2606}
2607
2608void btif_dm_proc_loc_oob(BOOLEAN valid, BT_OCTET16 c, BT_OCTET16 r)
2609{
2610    FILE *fp;
2611    char *path_a = "/data/misc/bluedroid/LOCAL/a.key";
2612    char *path_b = "/data/misc/bluedroid/LOCAL/b.key";
2613    char *path = NULL;
2614    char prop_oob[PROPERTY_VALUE_MAX];
2615    BTIF_TRACE_DEBUG("btif_dm_proc_loc_oob: valid=%d", valid);
2616    if (oob_cb.sp_c[0] == 0 && oob_cb.sp_c[1] == 0 &&
2617        oob_cb.sp_c[2] == 0 && oob_cb.sp_c[3] == 0 &&
2618        valid)
2619    {
2620        BTIF_TRACE_DEBUG("save local OOB data in memory");
2621        memcpy(oob_cb.sp_c, c, BT_OCTET16_LEN);
2622        memcpy(oob_cb.sp_r, r, BT_OCTET16_LEN);
2623        property_get("service.brcm.bt.oob", prop_oob, "3");
2624        BTIF_TRACE_DEBUG("btif_dm_proc_loc_oob prop_oob = %s",prop_oob);
2625        if (prop_oob[0] == '1')
2626            path = path_a;
2627        else if (prop_oob[0] == '2')
2628            path = path_b;
2629        if (path)
2630        {
2631            fp = fopen(path, "wb+");
2632            if (fp == NULL)
2633            {
2634                BTIF_TRACE_DEBUG("btif_dm_proc_loc_oob: failed to save local OOB data to %s", path);
2635            }
2636            else
2637            {
2638                BTIF_TRACE_DEBUG("btif_dm_proc_loc_oob: save local OOB data into file %s",path);
2639                fwrite (c , 1 , BT_OCTET16_LEN , fp );
2640                fwrite (r , 1 , BT_OCTET16_LEN , fp );
2641                fclose(fp);
2642            }
2643        }
2644    }
2645}
2646BOOLEAN btif_dm_proc_rmt_oob(BD_ADDR bd_addr,  BT_OCTET16 p_c, BT_OCTET16 p_r)
2647{
2648    char t[128];
2649    FILE *fp;
2650    char *path_a = "/data/misc/bluedroid/LOCAL/a.key";
2651    char *path_b = "/data/misc/bluedroid/LOCAL/b.key";
2652    char *path = NULL;
2653    char prop_oob[PROPERTY_VALUE_MAX];
2654    BOOLEAN result = FALSE;
2655    bt_bdaddr_t bt_bd_addr;
2656    bdcpy(oob_cb.oob_bdaddr, bd_addr);
2657    property_get("service.brcm.bt.oob", prop_oob, "3");
2658    BTIF_TRACE_DEBUG("btif_dm_proc_rmt_oob prop_oob = %s",prop_oob);
2659    if (prop_oob[0] == '1')
2660        path = path_b;
2661    else if (prop_oob[0] == '2')
2662        path = path_a;
2663    if (path)
2664    {
2665        fp = fopen(path, "rb");
2666        if (fp == NULL)
2667        {
2668            BTIF_TRACE_DEBUG("btapp_dm_rmt_oob_reply: failed to read OOB keys from %s",path);
2669            return FALSE;
2670        }
2671        else
2672        {
2673            BTIF_TRACE_DEBUG("btif_dm_proc_rmt_oob: read OOB data from %s",path);
2674            fread (p_c , 1 , BT_OCTET16_LEN , fp );
2675            fread (p_r , 1 , BT_OCTET16_LEN , fp );
2676            fclose(fp);
2677        }
2678        BTIF_TRACE_DEBUG("----btif_dm_proc_rmt_oob: TRUE");
2679        sprintf(t, "%02x:%02x:%02x:%02x:%02x:%02x",
2680                oob_cb.oob_bdaddr[0], oob_cb.oob_bdaddr[1], oob_cb.oob_bdaddr[2],
2681                oob_cb.oob_bdaddr[3], oob_cb.oob_bdaddr[4], oob_cb.oob_bdaddr[5]);
2682        BTIF_TRACE_DEBUG("----btif_dm_proc_rmt_oob: peer_bdaddr = %s", t);
2683        sprintf(t, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
2684                p_c[0], p_c[1], p_c[2],  p_c[3],  p_c[4],  p_c[5],  p_c[6],  p_c[7],
2685                p_c[8], p_c[9], p_c[10], p_c[11], p_c[12], p_c[13], p_c[14], p_c[15]);
2686        BTIF_TRACE_DEBUG("----btif_dm_proc_rmt_oob: c = %s",t);
2687        sprintf(t, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
2688                p_r[0], p_r[1], p_r[2],  p_r[3],  p_r[4],  p_r[5],  p_r[6],  p_r[7],
2689                p_r[8], p_r[9], p_r[10], p_r[11], p_r[12], p_r[13], p_r[14], p_r[15]);
2690        BTIF_TRACE_DEBUG("----btif_dm_proc_rmt_oob: r = %s",t);
2691        bdcpy(bt_bd_addr.address, bd_addr);
2692        btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_BOND_STATE_BONDING,
2693                              (char *)&bt_bd_addr, sizeof(bt_bdaddr_t), NULL);
2694        result = TRUE;
2695    }
2696    BTIF_TRACE_DEBUG("btif_dm_proc_rmt_oob result=%d",result);
2697    return result;
2698}
2699#endif /*  BTIF_DM_OOB_TEST */
2700#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
2701
2702static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF *p_ssp_key_notif)
2703{
2704    bt_bdaddr_t bd_addr;
2705    bt_bdname_t bd_name;
2706    UINT32 cod;
2707
2708    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
2709
2710    /* Remote name update */
2711    btif_update_remote_properties(p_ssp_key_notif->bd_addr , p_ssp_key_notif->bd_name,
2712                                          NULL, BT_DEVICE_TYPE_BLE);
2713    bdcpy(bd_addr.address, p_ssp_key_notif->bd_addr);
2714    memcpy(bd_name.name, p_ssp_key_notif->bd_name, BD_NAME_LEN);
2715
2716    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
2717    pairing_cb.is_ssp = FALSE;
2718    cod = COD_UNCLASSIFIED;
2719
2720    HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name,
2721              cod, BT_SSP_VARIANT_PASSKEY_NOTIFICATION,
2722              p_ssp_key_notif->passkey);
2723}
2724
2725/*******************************************************************************
2726**
2727** Function         btif_dm_ble_auth_cmpl_evt
2728**
2729** Description      Executes authentication complete event in btif context
2730**
2731** Returns          void
2732**
2733*******************************************************************************/
2734static void btif_dm_ble_auth_cmpl_evt (tBTA_DM_AUTH_CMPL *p_auth_cmpl)
2735{
2736    /* Save link key, if not temporary */
2737    bt_bdaddr_t bd_addr;
2738    bt_status_t status = BT_STATUS_FAIL;
2739    bt_bond_state_t state = BT_BOND_STATE_NONE;
2740
2741    bdcpy(bd_addr.address, p_auth_cmpl->bd_addr);
2742    if ( (p_auth_cmpl->success == TRUE) && (p_auth_cmpl->key_present) )
2743    {
2744        /* store keys */
2745    }
2746    if (p_auth_cmpl->success)
2747    {
2748        status = BT_STATUS_SUCCESS;
2749        state = BT_BOND_STATE_BONDED;
2750
2751        btif_dm_save_ble_bonding_keys();
2752        BTA_GATTC_Refresh(bd_addr.address);
2753        btif_dm_get_remote_services(&bd_addr);
2754    }
2755    else
2756    {
2757        /*Map the HCI fail reason  to  bt status  */
2758        switch (p_auth_cmpl->fail_reason)
2759        {
2760            case BTA_DM_AUTH_SMP_PAIR_AUTH_FAIL:
2761            case BTA_DM_AUTH_SMP_CONFIRM_VALUE_FAIL:
2762                btif_dm_remove_ble_bonding_keys();
2763                status = BT_STATUS_AUTH_FAILURE;
2764                break;
2765            case BTA_DM_AUTH_SMP_PAIR_NOT_SUPPORT:
2766                status = BT_STATUS_AUTH_REJECTED;
2767                break;
2768            default:
2769                btif_dm_remove_ble_bonding_keys();
2770                status =  BT_STATUS_FAIL;
2771                break;
2772        }
2773    }
2774    bond_state_changed(status, &bd_addr, state);
2775}
2776
2777
2778
2779void    btif_dm_load_ble_local_keys(void)
2780{
2781    bt_status_t bt_status;
2782
2783    memset(&ble_local_key_cb, 0, sizeof(btif_dm_local_key_cb_t));
2784
2785    if (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_ER,(char*)&ble_local_key_cb.er[0],
2786                                       BT_OCTET16_LEN)== BT_STATUS_SUCCESS)
2787    {
2788        ble_local_key_cb.is_er_rcvd = TRUE;
2789        BTIF_TRACE_DEBUG("%s BLE ER key loaded",__FUNCTION__ );
2790    }
2791
2792    if ((btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IR,(char*)&ble_local_key_cb.id_keys.ir[0],
2793                                        BT_OCTET16_LEN)== BT_STATUS_SUCCESS )&&
2794        (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IRK, (char*)&ble_local_key_cb.id_keys.irk[0],
2795                                        BT_OCTET16_LEN)== BT_STATUS_SUCCESS)&&
2796        (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_DHK,(char*)&ble_local_key_cb.id_keys.dhk[0],
2797                                        BT_OCTET16_LEN)== BT_STATUS_SUCCESS))
2798    {
2799        ble_local_key_cb.is_id_keys_rcvd = TRUE;
2800        BTIF_TRACE_DEBUG("%s BLE ID keys loaded",__FUNCTION__ );
2801    }
2802
2803}
2804void    btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK *p_key_mask, BT_OCTET16 er,
2805                                   tBTA_BLE_LOCAL_ID_KEYS *p_id_keys)
2806{
2807    if (ble_local_key_cb.is_er_rcvd )
2808    {
2809        memcpy(&er[0], &ble_local_key_cb.er[0], sizeof(BT_OCTET16));
2810        *p_key_mask |= BTA_BLE_LOCAL_KEY_TYPE_ER;
2811    }
2812
2813    if (ble_local_key_cb.is_id_keys_rcvd)
2814    {
2815        memcpy(&p_id_keys->ir[0], &ble_local_key_cb.id_keys.ir[0], sizeof(BT_OCTET16));
2816        memcpy(&p_id_keys->irk[0],  &ble_local_key_cb.id_keys.irk[0], sizeof(BT_OCTET16));
2817        memcpy(&p_id_keys->dhk[0],  &ble_local_key_cb.id_keys.dhk[0], sizeof(BT_OCTET16));
2818        *p_key_mask |= BTA_BLE_LOCAL_KEY_TYPE_ID;
2819    }
2820    BTIF_TRACE_DEBUG("%s  *p_key_mask=0x%02x",__FUNCTION__,   *p_key_mask);
2821}
2822
2823void btif_dm_save_ble_bonding_keys(void)
2824{
2825
2826    bt_bdaddr_t bd_addr;
2827
2828    BTIF_TRACE_DEBUG("%s",__FUNCTION__ );
2829
2830    bdcpy(bd_addr.address, pairing_cb.bd_addr);
2831
2832    if (pairing_cb.ble.is_penc_key_rcvd)
2833    {
2834        btif_storage_add_ble_bonding_key(&bd_addr,
2835                                         (char *) &pairing_cb.ble.penc_key,
2836                                         BTIF_DM_LE_KEY_PENC,
2837                                         sizeof(btif_dm_ble_penc_keys_t));
2838    }
2839
2840    if (pairing_cb.ble.is_pid_key_rcvd)
2841    {
2842        btif_storage_add_ble_bonding_key(&bd_addr,
2843                                         (char *) &pairing_cb.ble.pid_key[0],
2844                                         BTIF_DM_LE_KEY_PID,
2845                                         BT_OCTET16_LEN);
2846    }
2847
2848
2849    if (pairing_cb.ble.is_pcsrk_key_rcvd)
2850    {
2851        btif_storage_add_ble_bonding_key(&bd_addr,
2852                                         (char *) &pairing_cb.ble.pcsrk_key,
2853                                         BTIF_DM_LE_KEY_PCSRK,
2854                                         sizeof(btif_dm_ble_pcsrk_keys_t));
2855    }
2856
2857
2858    if (pairing_cb.ble.is_lenc_key_rcvd)
2859    {
2860        btif_storage_add_ble_bonding_key(&bd_addr,
2861                                         (char *) &pairing_cb.ble.lenc_key,
2862                                         BTIF_DM_LE_KEY_LENC,
2863                                         sizeof(btif_dm_ble_lenc_keys_t));
2864    }
2865
2866    if (pairing_cb.ble.is_lcsrk_key_rcvd)
2867    {
2868        btif_storage_add_ble_bonding_key(&bd_addr,
2869                                         (char *) &pairing_cb.ble.lcsrk_key,
2870                                         BTIF_DM_LE_KEY_LCSRK,
2871                                         sizeof(btif_dm_ble_lcsrk_keys_t));
2872    }
2873
2874}
2875
2876
2877void btif_dm_remove_ble_bonding_keys(void)
2878{
2879    bt_bdaddr_t bd_addr;
2880
2881    BTIF_TRACE_DEBUG("%s",__FUNCTION__ );
2882
2883    bdcpy(bd_addr.address, pairing_cb.bd_addr);
2884    btif_storage_remove_ble_bonding_keys(&bd_addr);
2885}
2886
2887
2888/*******************************************************************************
2889**
2890** Function         btif_dm_ble_sec_req_evt
2891**
2892** Description      Eprocess security request event in btif context
2893**
2894** Returns          void
2895**
2896*******************************************************************************/
2897void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ *p_ble_req)
2898{
2899    bt_bdaddr_t bd_addr;
2900    bt_bdname_t bd_name;
2901    UINT32 cod;
2902    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
2903
2904    if (pairing_cb.state == BT_BOND_STATE_BONDING)
2905    {
2906        BTIF_TRACE_DEBUG("%s Discard security request", __FUNCTION__);
2907        return;
2908    }
2909
2910    /* Remote name update */
2911    btif_update_remote_properties(p_ble_req->bd_addr,p_ble_req->bd_name,NULL,BT_DEVICE_TYPE_BLE);
2912
2913    bdcpy(bd_addr.address, p_ble_req->bd_addr);
2914    memcpy(bd_name.name, p_ble_req->bd_name, BD_NAME_LEN);
2915
2916    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
2917
2918    pairing_cb.is_temp = FALSE;
2919    pairing_cb.is_le_only = TRUE;
2920    pairing_cb.is_ssp = TRUE;
2921
2922    cod = COD_UNCLASSIFIED;
2923
2924    HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name, cod,
2925              BT_SSP_VARIANT_CONSENT, 0);
2926}
2927
2928
2929
2930/*******************************************************************************
2931**
2932** Function         btif_dm_ble_passkey_req_evt
2933**
2934** Description      Executes pin request event in btif context
2935**
2936** Returns          void
2937**
2938*******************************************************************************/
2939static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ *p_pin_req)
2940{
2941    bt_bdaddr_t bd_addr;
2942    bt_bdname_t bd_name;
2943    UINT32 cod;
2944
2945    /* Remote name update */
2946    btif_update_remote_properties(p_pin_req->bd_addr,p_pin_req->bd_name,NULL,BT_DEVICE_TYPE_BLE);
2947
2948    bdcpy(bd_addr.address, p_pin_req->bd_addr);
2949    memcpy(bd_name.name, p_pin_req->bd_name, BD_NAME_LEN);
2950
2951    bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
2952    pairing_cb.is_le_only = TRUE;
2953
2954    cod = COD_UNCLASSIFIED;
2955
2956    HAL_CBACK(bt_hal_cbacks, pin_request_cb,
2957              &bd_addr, &bd_name, cod);
2958}
2959
2960
2961void btif_dm_update_ble_remote_properties( BD_ADDR bd_addr, BD_NAME bd_name,
2962                                           tBT_DEVICE_TYPE dev_type)
2963{
2964   btif_update_remote_properties(bd_addr,bd_name,NULL,dev_type);
2965}
2966
2967static void btif_dm_ble_tx_test_cback(void *p)
2968{
2969    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_LE_TX_TEST,
2970                          (char *)p, 1, NULL);
2971}
2972
2973static void btif_dm_ble_rx_test_cback(void *p)
2974{
2975    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_LE_RX_TEST,
2976                          (char *)p, 1, NULL);
2977}
2978
2979static void btif_dm_ble_test_end_cback(void *p)
2980{
2981    btif_transfer_context(btif_dm_generic_evt, BTIF_DM_CB_LE_TEST_END,
2982                          (char *)p, 3, NULL);
2983}
2984/*******************************************************************************
2985**
2986** Function         btif_le_test_mode
2987**
2988** Description     Sends a HCI BLE Test command to the Controller
2989**
2990** Returns          BT_STATUS_SUCCESS on success
2991**
2992*******************************************************************************/
2993bt_status_t btif_le_test_mode(uint16_t opcode, uint8_t *buf, uint8_t len)
2994{
2995     switch (opcode) {
2996         case HCI_BLE_TRANSMITTER_TEST:
2997             if (len != 3) return BT_STATUS_PARM_INVALID;
2998             BTM_BleTransmitterTest(buf[0],buf[1],buf[2], btif_dm_ble_tx_test_cback);
2999             break;
3000         case HCI_BLE_RECEIVER_TEST:
3001             if (len != 1) return BT_STATUS_PARM_INVALID;
3002             BTM_BleReceiverTest(buf[0], btif_dm_ble_rx_test_cback);
3003             break;
3004         case HCI_BLE_TEST_END:
3005             BTM_BleTestEnd((tBTM_CMPL_CB*) btif_dm_ble_test_end_cback);
3006             break;
3007         default:
3008             BTIF_TRACE_ERROR("%s: Unknown LE Test Mode Command 0x%x", __FUNCTION__, opcode);
3009             return BT_STATUS_UNSUPPORTED;
3010     }
3011     return BT_STATUS_SUCCESS;
3012}
3013
3014#endif
3015
3016void btif_dm_on_disable()
3017{
3018    /* cancel any pending pairing requests */
3019    if (pairing_cb.state == BT_BOND_STATE_BONDING)
3020    {
3021        bt_bdaddr_t bd_addr;
3022
3023        BTIF_TRACE_DEBUG("%s: Cancel pending pairing request", __FUNCTION__);
3024        bdcpy(bd_addr.address, pairing_cb.bd_addr);
3025        btif_dm_cancel_bond(&bd_addr);
3026    }
3027}
3028
3029/*******************************************************************************
3030**
3031** Function         btif_dm_read_energy_info
3032**
3033** Description     Reads the energy info from controller
3034**
3035** Returns         void
3036**
3037*******************************************************************************/
3038void btif_dm_read_energy_info()
3039{
3040#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
3041    BTA_DmBleGetEnergyInfo(bta_energy_info_cb);
3042#endif
3043}
3044
3045static char* btif_get_default_local_name() {
3046    if (btif_default_local_name[0] == '\0')
3047    {
3048        int max_len = sizeof(btif_default_local_name) - 1;
3049        if (BTM_DEF_LOCAL_NAME[0] != '\0')
3050        {
3051            strncpy(btif_default_local_name, BTM_DEF_LOCAL_NAME, max_len);
3052        }
3053        else
3054        {
3055            char prop_model[PROPERTY_VALUE_MAX];
3056            property_get(PROPERTY_PRODUCT_MODEL, prop_model, "");
3057            strncpy(btif_default_local_name, prop_model, max_len);
3058        }
3059        btif_default_local_name[max_len] = '\0';
3060    }
3061    return btif_default_local_name;
3062}
3063