OSDN Git Service

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