OSDN Git Service

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