OSDN Git Service

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