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