OSDN Git Service

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