OSDN Git Service

merge in m-wireless-internal-release history after reset to d232721ae5e5b6949a5249f0d...
[android-x86/system-bt.git] / stack / btm / btm_ble.c
1 /******************************************************************************
2  *
3  *  Copyright (C) 1999-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  *  This file contains functions for BLE device control utilities, and LE
22  *  security functions.
23  *
24  ******************************************************************************/
25 #include "bt_target.h"
26
27 #if BLE_INCLUDED == TRUE
28
29 #include <string.h>
30
31 #include "bt_types.h"
32 #include "hcimsgs.h"
33 #include "btu.h"
34 #include "btm_int.h"
35 #include "btm_ble_api.h"
36 #include "smp_api.h"
37 #include "l2c_int.h"
38 #include "gap_api.h"
39 #include "bt_utils.h"
40 #include "device/include/controller.h"
41 #define LOG_TAG "bt_btm_ble"
42 #include "osi/include/log.h"
43
44 #if SMP_INCLUDED == TRUE
45 extern BOOLEAN aes_cipher_msg_auth_code(BT_OCTET16 key, UINT8 *input, UINT16 length,
46                                                  UINT16 tlen, UINT8 *p_signature);
47 extern void smp_link_encrypted(BD_ADDR bda, UINT8 encr_enable);
48 extern BOOLEAN smp_proc_ltk_request(BD_ADDR bda);
49 #endif
50 extern void gatt_notify_enc_cmpl(BD_ADDR bd_addr);
51 /*******************************************************************************/
52 /* External Function to be called by other modules                             */
53 /*******************************************************************************/
54 /********************************************************
55 **
56 ** Function         BTM_SecAddBleDevice
57 **
58 ** Description      Add/modify device.  This function will be normally called
59 **                  during host startup to restore all required information
60 **                  for a LE device stored in the NVRAM.
61 **
62 ** Parameters:      bd_addr          - BD address of the peer
63 **                  bd_name          - Name of the peer device.  NULL if unknown.
64 **                  dev_type         - Remote device's device type.
65 **                  addr_type        - LE device address type.
66 **
67 ** Returns          TRUE if added OK, else FALSE
68 **
69 *******************************************************************************/
70 BOOLEAN BTM_SecAddBleDevice (BD_ADDR bd_addr, BD_NAME bd_name, tBT_DEVICE_TYPE dev_type,
71                              tBLE_ADDR_TYPE addr_type)
72 {
73     tBTM_SEC_DEV_REC  *p_dev_rec;
74     UINT8               i = 0;
75     tBTM_INQ_INFO      *p_info=NULL;
76
77     BTM_TRACE_DEBUG ("BTM_SecAddBleDevice dev_type=0x%x", dev_type);
78     p_dev_rec = btm_find_dev (bd_addr);
79
80     if (!p_dev_rec)
81     {
82         BTM_TRACE_DEBUG("Add a new device");
83
84         /* There is no device record, allocate one.
85          * If we can not find an empty spot for this one, let it fail. */
86         for (i = 0; i < BTM_SEC_MAX_DEVICE_RECORDS; i++)
87         {
88             if (!(btm_cb.sec_dev_rec[i].sec_flags & BTM_SEC_IN_USE))
89             {
90                 BTM_TRACE_DEBUG ("allocate a new dev rec idx=0x%x ", i );
91                 p_dev_rec = &btm_cb.sec_dev_rec[i];
92
93                 /* Mark this record as in use and initialize */
94                 memset (p_dev_rec, 0, sizeof (tBTM_SEC_DEV_REC));
95                 p_dev_rec->sec_flags = BTM_SEC_IN_USE;
96                 memcpy (p_dev_rec->bd_addr, bd_addr, BD_ADDR_LEN);
97                 p_dev_rec->hci_handle = BTM_GetHCIConnHandle (bd_addr, BT_TRANSPORT_BR_EDR);
98                 p_dev_rec->ble_hci_handle = BTM_GetHCIConnHandle (bd_addr, BT_TRANSPORT_LE);
99
100                 /* update conn params, use default value for background connection params */
101                 p_dev_rec->conn_params.min_conn_int     =
102                 p_dev_rec->conn_params.max_conn_int     =
103                 p_dev_rec->conn_params.supervision_tout =
104                 p_dev_rec->conn_params.slave_latency    = BTM_BLE_CONN_PARAM_UNDEF;
105
106                 BTM_TRACE_DEBUG ("hci_handl=0x%x ",  p_dev_rec->ble_hci_handle );
107                 break;
108             }
109         }
110
111         if (!p_dev_rec)
112             return(FALSE);
113     }
114     else
115     {
116         BTM_TRACE_DEBUG("Device already exist");
117     }
118
119     memset(p_dev_rec->sec_bd_name, 0, sizeof(tBTM_BD_NAME));
120
121     if (bd_name && bd_name[0])
122     {
123         p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
124         BCM_STRNCPY_S ((char *)p_dev_rec->sec_bd_name, sizeof (p_dev_rec->sec_bd_name),
125                        (char *)bd_name, BTM_MAX_REM_BD_NAME_LEN);
126     }
127     p_dev_rec->device_type = dev_type;
128     p_dev_rec->ble.ble_addr_type = addr_type;
129     BTM_TRACE_DEBUG ("p_dev_rec->device_type =0x%x  addr_type=0x%x sec_flags=0x%x",
130                       dev_type,  addr_type, p_dev_rec->sec_flags);
131
132     /* sync up with the Inq Data base*/
133     p_info = BTM_InqDbRead(bd_addr);
134     if (p_info)
135     {
136         p_info->results.ble_addr_type = p_dev_rec->ble.ble_addr_type ;
137         p_info->results.device_type = p_dev_rec->device_type;
138         BTM_TRACE_DEBUG ("InqDb  device_type =0x%x  addr_type=0x%x",
139                           p_info->results.device_type, p_info->results.ble_addr_type);
140     }
141
142     return(TRUE);
143 }
144
145 /*******************************************************************************
146 **
147 ** Function         BTM_SecAddBleKey
148 **
149 ** Description      Add/modify LE device information.  This function will be
150 **                  normally called during host startup to restore all required
151 **                  information stored in the NVRAM.
152 **
153 ** Parameters:      bd_addr          - BD address of the peer
154 **                  p_le_key         - LE key values.
155 **                  key_type         - LE SMP key type.
156 *
157 ** Returns          TRUE if added OK, else FALSE
158 **
159 *******************************************************************************/
160 BOOLEAN BTM_SecAddBleKey (BD_ADDR bd_addr, tBTM_LE_KEY_VALUE *p_le_key, tBTM_LE_KEY_TYPE key_type)
161 {
162 #if SMP_INCLUDED == TRUE
163     tBTM_SEC_DEV_REC  *p_dev_rec;
164     BTM_TRACE_DEBUG ("BTM_SecAddBleKey");
165     p_dev_rec = btm_find_dev (bd_addr);
166     if (!p_dev_rec || !p_le_key ||
167         (key_type != BTM_LE_KEY_PENC && key_type != BTM_LE_KEY_PID &&
168          key_type != BTM_LE_KEY_PCSRK && key_type != BTM_LE_KEY_LENC &&
169          key_type != BTM_LE_KEY_LCSRK && key_type != BTM_LE_KEY_LID))
170     {
171         BTM_TRACE_WARNING ("BTM_SecAddBleKey()  Wrong Type, or No Device record \
172                         for bdaddr: %08x%04x, Type: %d",
173                             (bd_addr[0]<<24)+(bd_addr[1]<<16)+(bd_addr[2]<<8)+bd_addr[3],
174                             (bd_addr[4]<<8)+bd_addr[5], key_type);
175         return(FALSE);
176     }
177
178     BTM_TRACE_DEBUG ("BTM_SecAddLeKey()  BDA: %08x%04x, Type: 0x%02x",
179                       (bd_addr[0]<<24)+(bd_addr[1]<<16)+(bd_addr[2]<<8)+bd_addr[3],
180                       (bd_addr[4]<<8)+bd_addr[5], key_type);
181
182     btm_sec_save_le_key (bd_addr, key_type, p_le_key, FALSE);
183
184 #if (BLE_PRIVACY_SPT == TRUE)
185     if (key_type == BTM_LE_KEY_PID || key_type == BTM_LE_KEY_LID)
186         btm_ble_resolving_list_load_dev (p_dev_rec);
187 #endif
188
189 #endif
190
191     return(TRUE);
192 }
193
194 /*******************************************************************************
195 **
196 ** Function         BTM_BleLoadLocalKeys
197 **
198 ** Description      Local local identity key, encryption root or sign counter.
199 **
200 ** Parameters:      key_type: type of key, can be BTM_BLE_KEY_TYPE_ID, BTM_BLE_KEY_TYPE_ER
201 **                            or BTM_BLE_KEY_TYPE_COUNTER.
202 **                  p_key: pointer to the key.
203 *
204 ** Returns          non2.
205 **
206 *******************************************************************************/
207 void BTM_BleLoadLocalKeys(UINT8 key_type, tBTM_BLE_LOCAL_KEYS *p_key)
208 {
209     tBTM_DEVCB *p_devcb = &btm_cb.devcb;
210     BTM_TRACE_DEBUG ("%s", __func__);
211     if (p_key != NULL)
212     {
213         switch (key_type)
214         {
215             case BTM_BLE_KEY_TYPE_ID:
216                 memcpy(&p_devcb->id_keys, &p_key->id_keys, sizeof(tBTM_BLE_LOCAL_ID_KEYS));
217                 break;
218
219             case BTM_BLE_KEY_TYPE_ER:
220                 memcpy(p_devcb->ble_encryption_key_value, p_key->er, sizeof(BT_OCTET16));
221                 break;
222
223             default:
224                 BTM_TRACE_ERROR("unknow local key type: %d", key_type);
225                 break;
226         }
227     }
228 }
229
230 /*******************************************************************************
231 **
232 ** Function         BTM_GetDeviceEncRoot
233 **
234 ** Description      This function is called to read the local device encryption
235 **                  root.
236 **
237 ** Returns          void
238 **                  the local device ER is copied into ble_encr_key_value
239 **
240 *******************************************************************************/
241 void BTM_GetDeviceEncRoot (BT_OCTET16 ble_encr_key_value)
242 {
243     BTM_TRACE_DEBUG ("%s", __func__);
244     memcpy (ble_encr_key_value, btm_cb.devcb.ble_encryption_key_value, BT_OCTET16_LEN);
245 }
246
247 /*******************************************************************************
248 **
249 ** Function         BTM_GetDeviceIDRoot
250 **
251 ** Description      This function is called to read the local device identity
252 **                  root.
253 **
254 ** Returns          void
255 **                  the local device IR is copied into irk
256 **
257 *******************************************************************************/
258 void BTM_GetDeviceIDRoot (BT_OCTET16 irk)
259 {
260     BTM_TRACE_DEBUG ("BTM_GetDeviceIDRoot ");
261
262     memcpy (irk, btm_cb.devcb.id_keys.irk, BT_OCTET16_LEN);
263 }
264
265 /*******************************************************************************
266 **
267 ** Function         BTM_GetDeviceDHK
268 **
269 ** Description      This function is called to read the local device DHK.
270 **
271 ** Returns          void
272 **                  the local device DHK is copied into dhk
273 **
274 *******************************************************************************/
275 void BTM_GetDeviceDHK (BT_OCTET16 dhk)
276 {
277     BTM_TRACE_DEBUG ("BTM_GetDeviceDHK");
278     memcpy (dhk, btm_cb.devcb.id_keys.dhk, BT_OCTET16_LEN);
279 }
280
281 /*******************************************************************************
282 **
283 ** Function         BTM_ReadConnectionAddr
284 **
285 ** Description      This function is called to get the local device address information
286 **                  .
287 **
288 ** Returns          void
289 **
290 *******************************************************************************/
291 void BTM_ReadConnectionAddr (BD_ADDR remote_bda, BD_ADDR local_conn_addr, tBLE_ADDR_TYPE *p_addr_type)
292 {
293     tACL_CONN       *p_acl = btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
294
295     if (p_acl == NULL)
296     {
297         BTM_TRACE_ERROR("No connection exist!");
298         return;
299     }
300     memcpy(local_conn_addr, p_acl->conn_addr, BD_ADDR_LEN);
301     * p_addr_type = p_acl->conn_addr_type;
302
303     BTM_TRACE_DEBUG ("BTM_ReadConnectionAddr address type: %d addr: 0x%02x",
304                     p_acl->conn_addr_type, p_acl->conn_addr[0]);
305 }
306
307 /*******************************************************************************
308 **
309 ** Function         BTM_IsBleConnection
310 **
311 ** Description      This function is called to check if the connection handle
312 **                  for an LE link
313 **
314 ** Returns          TRUE if connection is LE link, otherwise FALSE.
315 **
316 *******************************************************************************/
317 BOOLEAN BTM_IsBleConnection (UINT16 conn_handle)
318 {
319 #if (BLE_INCLUDED == TRUE)
320     UINT8                xx;
321     tACL_CONN            *p;
322
323     BTM_TRACE_API ("BTM_IsBleConnection: conn_handle: %d", conn_handle);
324
325     xx = btm_handle_to_acl_index (conn_handle);
326     if (xx >= MAX_L2CAP_LINKS)
327         return FALSE;
328
329     p = &btm_cb.acl_db[xx];
330
331     return (p->transport == BT_TRANSPORT_LE);
332 #else
333     return FALSE;
334 #endif
335 }
336
337 /*******************************************************************************
338 **
339 ** Function         BTM_ReadRemoteConnectionAddr
340 **
341 ** Description      This function is read the remote device address currently used
342 **
343 ** Parameters     pseudo_addr: pseudo random address available
344 **                conn_addr:connection address used
345 **                p_addr_type : BD Address type, Public or Random of the address used
346 **
347 ** Returns          BOOLEAN , TRUE if connection to remote device exists, else FALSE
348 **
349 *******************************************************************************/
350 BOOLEAN BTM_ReadRemoteConnectionAddr(BD_ADDR pseudo_addr, BD_ADDR conn_addr,
351                                                tBLE_ADDR_TYPE *p_addr_type)
352 {
353  BOOLEAN         st = TRUE;
354 #if (BLE_PRIVACY_SPT == TRUE)
355     tACL_CONN       *p = btm_bda_to_acl (pseudo_addr, BT_TRANSPORT_LE);
356
357     if (p == NULL)
358     {
359         BTM_TRACE_ERROR("BTM_ReadRemoteConnectionAddr can not find connection"
360                         " with matching address");
361         return FALSE;
362     }
363
364     memcpy(conn_addr, p->active_remote_addr, BD_ADDR_LEN);
365     *p_addr_type = p->active_remote_addr_type;
366 #else
367     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev(pseudo_addr);
368
369     memcpy(conn_addr, pseudo_addr, BD_ADDR_LEN);
370     if (p_dev_rec != NULL)
371     {
372         *p_addr_type = p_dev_rec->ble.ble_addr_type;
373     }
374 #endif
375     return st;
376
377 }
378 /*******************************************************************************
379 **
380 ** Function         BTM_SecurityGrant
381 **
382 ** Description      This function is called to grant security process.
383 **
384 ** Parameters       bd_addr - peer device bd address.
385 **                  res     - result of the operation BTM_SUCCESS if success.
386 **                            Otherwise, BTM_REPEATED_ATTEMPTS is too many attempts.
387 **
388 ** Returns          None
389 **
390 *******************************************************************************/
391 void BTM_SecurityGrant(BD_ADDR bd_addr, UINT8 res)
392 {
393 #if SMP_INCLUDED == TRUE
394     tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_REPEATED_ATTEMPTS;
395     BTM_TRACE_DEBUG ("BTM_SecurityGrant");
396     SMP_SecurityGrant(bd_addr, res_smp);
397 #endif
398 }
399
400 /*******************************************************************************
401 **
402 ** Function         BTM_BlePasskeyReply
403 **
404 ** Description      This function is called after Security Manager submitted
405 **                  passkey request to the application.
406 **
407 ** Parameters:      bd_addr      - Address of the device for which passkey was requested
408 **                  res          - result of the operation BTM_SUCCESS if success
409 **                  key_len      - length in bytes of the Passkey
410 **                  p_passkey        - pointer to array with the passkey
411 **                  trusted_mask - bitwise OR of trusted services (array of UINT32)
412 **
413 *******************************************************************************/
414 void BTM_BlePasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey)
415 {
416 #if SMP_INCLUDED == TRUE
417     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (bd_addr);
418     tSMP_STATUS      res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL;
419
420     if (p_dev_rec == NULL)
421     {
422         BTM_TRACE_ERROR("Passkey reply to Unknown device");
423         return;
424     }
425
426     p_dev_rec->sec_flags   |= BTM_SEC_LE_AUTHENTICATED;
427     BTM_TRACE_DEBUG ("BTM_BlePasskeyReply");
428     SMP_PasskeyReply(bd_addr, res_smp, passkey);
429 #endif
430 }
431
432 /*******************************************************************************
433 **
434 ** Function         BTM_BleConfirmReply
435 **
436 ** Description      This function is called after Security Manager submitted
437 **                  numeric comparison request to the application.
438 **
439 ** Parameters:      bd_addr      - Address of the device with which numeric
440 **                                 comparison was requested
441 **                  res          - comparison result BTM_SUCCESS if success
442 **
443 *******************************************************************************/
444 void BTM_BleConfirmReply (BD_ADDR bd_addr, UINT8 res)
445 {
446     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (bd_addr);
447     tSMP_STATUS      res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL;
448
449     if (p_dev_rec == NULL)
450     {
451         BTM_TRACE_ERROR("Passkey reply to Unknown device");
452         return;
453     }
454
455     p_dev_rec->sec_flags   |= BTM_SEC_LE_AUTHENTICATED;
456     BTM_TRACE_DEBUG ("%s", __func__);
457     SMP_ConfirmReply(bd_addr, res_smp);
458 }
459
460 /*******************************************************************************
461 **
462 ** Function         BTM_BleOobDataReply
463 **
464 ** Description      This function is called to provide the OOB data for
465 **                  SMP in response to BTM_LE_OOB_REQ_EVT
466 **
467 ** Parameters:      bd_addr     - Address of the peer device
468 **                  res         - result of the operation SMP_SUCCESS if success
469 **                  p_data      - simple pairing Randomizer  C.
470 **
471 *******************************************************************************/
472 void BTM_BleOobDataReply(BD_ADDR bd_addr, UINT8 res, UINT8 len, UINT8 *p_data)
473 {
474 #if SMP_INCLUDED == TRUE
475     tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_OOB_FAIL;
476     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (bd_addr);
477
478     BTM_TRACE_DEBUG ("BTM_BleOobDataReply");
479
480     if (p_dev_rec == NULL)
481     {
482         BTM_TRACE_ERROR("BTM_BleOobDataReply() to Unknown device");
483         return;
484     }
485
486     p_dev_rec->sec_flags |= BTM_SEC_LE_AUTHENTICATED;
487     SMP_OobDataReply(bd_addr, res_smp, len, p_data);
488 #endif
489 }
490
491 /******************************************************************************
492 **
493 ** Function         BTM_BleSetConnScanParams
494 **
495 ** Description      Set scan parameter used in BLE connection request
496 **
497 ** Parameters:      scan_interval: scan interval
498 **                  scan_window: scan window
499 **
500 ** Returns          void
501 **
502 *******************************************************************************/
503 void BTM_BleSetConnScanParams (UINT16 scan_interval, UINT16 scan_window)
504 {
505 #if SMP_INCLUDED == TRUE
506     tBTM_BLE_CB *p_ble_cb = &btm_cb.ble_ctr_cb;
507     BOOLEAN     new_param = FALSE;
508
509     if (BTM_BLE_VALID_PRAM(scan_interval, BTM_BLE_SCAN_INT_MIN, BTM_BLE_SCAN_INT_MAX) &&
510         BTM_BLE_VALID_PRAM(scan_window, BTM_BLE_SCAN_WIN_MIN, BTM_BLE_SCAN_WIN_MAX))
511     {
512         if (p_ble_cb->scan_int != scan_interval)
513         {
514             p_ble_cb->scan_int = scan_interval;
515             new_param = TRUE;
516         }
517
518         if (p_ble_cb->scan_win != scan_window)
519         {
520             p_ble_cb->scan_win = scan_window;
521             new_param = TRUE;
522         }
523
524         if (new_param && p_ble_cb->conn_state == BLE_BG_CONN)
525         {
526             btm_ble_suspend_bg_conn();
527         }
528     }
529     else
530     {
531         BTM_TRACE_ERROR("Illegal Connection Scan Parameters");
532     }
533 #endif
534 }
535
536 /********************************************************
537 **
538 ** Function         BTM_BleSetPrefConnParams
539 **
540 ** Description      Set a peripheral's preferred connection parameters
541 **
542 ** Parameters:      bd_addr          - BD address of the peripheral
543 **                  scan_interval: scan interval
544 **                  scan_window: scan window
545 **                  min_conn_int     - minimum preferred connection interval
546 **                  max_conn_int     - maximum preferred connection interval
547 **                  slave_latency    - preferred slave latency
548 **                  supervision_tout - preferred supervision timeout
549 **
550 ** Returns          void
551 **
552 *******************************************************************************/
553 void BTM_BleSetPrefConnParams (BD_ADDR bd_addr,
554                                UINT16 min_conn_int, UINT16 max_conn_int,
555                                UINT16 slave_latency, UINT16 supervision_tout)
556 {
557     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (bd_addr);
558
559     BTM_TRACE_API ("BTM_BleSetPrefConnParams min: %u  max: %u  latency: %u  \
560                     tout: %u",
561                     min_conn_int, max_conn_int, slave_latency, supervision_tout);
562
563     if (BTM_BLE_VALID_PRAM(min_conn_int, BTM_BLE_CONN_INT_MIN, BTM_BLE_CONN_INT_MAX) &&
564         BTM_BLE_VALID_PRAM(max_conn_int, BTM_BLE_CONN_INT_MIN, BTM_BLE_CONN_INT_MAX) &&
565         BTM_BLE_VALID_PRAM(supervision_tout, BTM_BLE_CONN_SUP_TOUT_MIN, BTM_BLE_CONN_SUP_TOUT_MAX) &&
566         (slave_latency <= BTM_BLE_CONN_LATENCY_MAX || slave_latency == BTM_BLE_CONN_PARAM_UNDEF))
567     {
568         if (p_dev_rec)
569         {
570             /* expect conn int and stout and slave latency to be updated all together */
571             if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF || max_conn_int != BTM_BLE_CONN_PARAM_UNDEF)
572             {
573                 if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF)
574                     p_dev_rec->conn_params.min_conn_int = min_conn_int;
575                 else
576                     p_dev_rec->conn_params.min_conn_int = max_conn_int;
577
578                 if (max_conn_int != BTM_BLE_CONN_PARAM_UNDEF)
579                     p_dev_rec->conn_params.max_conn_int = max_conn_int;
580                 else
581                     p_dev_rec->conn_params.max_conn_int = min_conn_int;
582
583                 if (slave_latency != BTM_BLE_CONN_PARAM_UNDEF)
584                     p_dev_rec->conn_params.slave_latency = slave_latency;
585                 else
586                     p_dev_rec->conn_params.slave_latency = BTM_BLE_CONN_SLAVE_LATENCY_DEF;
587
588                 if (supervision_tout != BTM_BLE_CONN_PARAM_UNDEF)
589                     p_dev_rec->conn_params.supervision_tout = supervision_tout;
590                 else
591                     p_dev_rec->conn_params.supervision_tout = BTM_BLE_CONN_TIMEOUT_DEF;
592
593             }
594
595         }
596         else
597         {
598             BTM_TRACE_ERROR("Unknown Device, setting rejected");
599         }
600     }
601     else
602     {
603         BTM_TRACE_ERROR("Illegal Connection Parameters");
604     }
605 }
606
607 /*******************************************************************************
608 **
609 ** Function         BTM_ReadDevInfo
610 **
611 ** Description      This function is called to read the device/address type
612 **                  of BD address.
613 **
614 ** Parameter        remote_bda: remote device address
615 **                  p_dev_type: output parameter to read the device type.
616 **                  p_addr_type: output parameter to read the address type.
617 **
618 *******************************************************************************/
619 void BTM_ReadDevInfo (BD_ADDR remote_bda, tBT_DEVICE_TYPE *p_dev_type, tBLE_ADDR_TYPE *p_addr_type)
620 {
621     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (remote_bda);
622     tBTM_INQ_INFO     *p_inq_info = BTM_InqDbRead(remote_bda);
623
624     *p_dev_type = BT_DEVICE_TYPE_BREDR;
625     *p_addr_type = BLE_ADDR_PUBLIC;
626
627     if (!p_dev_rec)
628     {
629         /* Check with the BT manager if details about remote device are known */
630         if (p_inq_info != NULL)
631         {
632             *p_dev_type = p_inq_info->results.device_type ;
633             *p_addr_type = p_inq_info->results.ble_addr_type;
634         } else {
635             /* unknown device, assume BR/EDR */
636             BTM_TRACE_DEBUG ("btm_find_dev_type - unknown device, BR/EDR assumed");
637         }
638     }
639     else /* there is a security device record exisitng */
640     {
641         /* new inquiry result, overwrite device type in security device record */
642         if (p_inq_info)
643         {
644             p_dev_rec->device_type          = p_inq_info->results.device_type;
645             p_dev_rec->ble.ble_addr_type    = p_inq_info->results.ble_addr_type;
646         }
647         *p_dev_type = p_dev_rec->device_type;
648         *p_addr_type = p_dev_rec->ble.ble_addr_type;
649
650     }
651
652     BTM_TRACE_DEBUG ("btm_find_dev_type - device_type = %d addr_type = %d", *p_dev_type , *p_addr_type);
653 }
654
655 /*******************************************************************************
656 **
657 ** Function         BTM_BleReceiverTest
658 **
659 ** Description      This function is called to start the LE Receiver test
660 **
661 ** Parameter       rx_freq - Frequency Range
662 **               p_cmd_cmpl_cback - Command Complete callback
663 **
664 *******************************************************************************/
665 void BTM_BleReceiverTest(UINT8 rx_freq, tBTM_CMPL_CB *p_cmd_cmpl_cback)
666 {
667      btm_cb.devcb.p_le_test_cmd_cmpl_cb = p_cmd_cmpl_cback;
668
669      if (btsnd_hcic_ble_receiver_test(rx_freq) == FALSE)
670      {
671           BTM_TRACE_ERROR("%s: Unable to Trigger LE receiver test", __FUNCTION__);
672      }
673 }
674
675 /*******************************************************************************
676 **
677 ** Function         BTM_BleTransmitterTest
678 **
679 ** Description      This function is called to start the LE Transmitter test
680 **
681 ** Parameter       tx_freq - Frequency Range
682 **                       test_data_len - Length in bytes of payload data in each packet
683 **                       packet_payload - Pattern to use in the payload
684 **                       p_cmd_cmpl_cback - Command Complete callback
685 **
686 *******************************************************************************/
687 void BTM_BleTransmitterTest(UINT8 tx_freq, UINT8 test_data_len,
688                                  UINT8 packet_payload, tBTM_CMPL_CB *p_cmd_cmpl_cback)
689 {
690      btm_cb.devcb.p_le_test_cmd_cmpl_cb = p_cmd_cmpl_cback;
691      if (btsnd_hcic_ble_transmitter_test(tx_freq, test_data_len, packet_payload) == FALSE)
692      {
693           BTM_TRACE_ERROR("%s: Unable to Trigger LE transmitter test", __FUNCTION__);
694      }
695 }
696
697 /*******************************************************************************
698 **
699 ** Function         BTM_BleTestEnd
700 **
701 ** Description      This function is called to stop the in-progress TX or RX test
702 **
703 ** Parameter       p_cmd_cmpl_cback - Command complete callback
704 **
705 *******************************************************************************/
706 void BTM_BleTestEnd(tBTM_CMPL_CB *p_cmd_cmpl_cback)
707 {
708      btm_cb.devcb.p_le_test_cmd_cmpl_cb = p_cmd_cmpl_cback;
709
710      if (btsnd_hcic_ble_test_end() == FALSE)
711      {
712           BTM_TRACE_ERROR("%s: Unable to End the LE TX/RX test", __FUNCTION__);
713      }
714 }
715
716 /*******************************************************************************
717 ** Internal Functions
718 *******************************************************************************/
719 void btm_ble_test_command_complete(UINT8 *p)
720 {
721     tBTM_CMPL_CB   *p_cb = btm_cb.devcb.p_le_test_cmd_cmpl_cb;
722     UINT8           status;
723
724     btm_cb.devcb.p_le_test_cmd_cmpl_cb = NULL;
725
726     if (p_cb)
727     {
728         (*p_cb)(p);
729     }
730 }
731
732 /*******************************************************************************
733 **
734 ** Function         BTM_UseLeLink
735 **
736 ** Description      This function is to select the underneath physical link to use.
737 **
738 ** Returns          TRUE to use LE, FALSE use BR/EDR.
739 **
740 *******************************************************************************/
741 BOOLEAN BTM_UseLeLink (BD_ADDR bd_addr)
742 {
743     tACL_CONN         *p;
744     tBT_DEVICE_TYPE     dev_type;
745     tBLE_ADDR_TYPE      addr_type;
746     BOOLEAN             use_le = FALSE;
747
748     if ((p = btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR)) != NULL)
749     {
750         return use_le;
751     }
752     else if ((p = btm_bda_to_acl(bd_addr, BT_TRANSPORT_LE)) != NULL)
753     {
754         use_le = TRUE;
755     }
756     else
757     {
758         BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type);
759         use_le = (dev_type == BT_DEVICE_TYPE_BLE);
760     }
761     return use_le;
762 }
763 /*******************************************************************************
764 **
765 ** Function         btm_ble_rand_enc_complete
766 **
767 ** Description      This function is the callback functions for HCI_Rand command
768 **                  and HCI_Encrypt command is completed.
769 **                  This message is received from the HCI.
770 **
771 ** Returns          void
772 **
773 *******************************************************************************/
774 void btm_ble_rand_enc_complete (UINT8 *p, UINT16 op_code, tBTM_RAND_ENC_CB *p_enc_cplt_cback)
775 {
776     tBTM_RAND_ENC   params;
777     UINT8           *p_dest = params.param_buf;
778
779     BTM_TRACE_DEBUG ("btm_ble_rand_enc_complete");
780
781     memset(&params, 0, sizeof(tBTM_RAND_ENC));
782
783     /* If there was a callback address for vcs complete, call it */
784     if (p_enc_cplt_cback && p)
785     {
786         /* Pass paramters to the callback function */
787         STREAM_TO_UINT8(params.status, p); /* command status */
788
789         if (params.status == HCI_SUCCESS)
790         {
791             params.opcode = op_code;
792
793             if (op_code == HCI_BLE_RAND)
794                 params.param_len = BT_OCTET8_LEN;
795             else
796                 params.param_len = BT_OCTET16_LEN;
797
798             memcpy(p_dest, p, params.param_len);  /* Fetch return info from HCI event message */
799         }
800         if (p_enc_cplt_cback)
801             (*p_enc_cplt_cback)(&params);  /* Call the Encryption complete callback function */
802     }
803 }
804
805
806     #if (SMP_INCLUDED == TRUE)
807
808 /*******************************************************************************
809 **
810 ** Function         btm_ble_get_enc_key_type
811 **
812 ** Description      This function is to increment local sign counter
813 ** Returns         None
814 **
815 *******************************************************************************/
816 void btm_ble_increment_sign_ctr(BD_ADDR bd_addr, BOOLEAN is_local )
817 {
818     tBTM_SEC_DEV_REC *p_dev_rec;
819
820     BTM_TRACE_DEBUG ("btm_ble_increment_sign_ctr is_local=%d", is_local);
821
822     if ((p_dev_rec = btm_find_dev (bd_addr)) != NULL)
823     {
824         if (is_local)
825             p_dev_rec->ble.keys.local_counter++;
826         else
827             p_dev_rec->ble.keys.counter++;
828         BTM_TRACE_DEBUG ("is_local=%d local sign counter=%d peer sign counter=%d",
829                           is_local,
830                           p_dev_rec->ble.keys.local_counter,
831                           p_dev_rec->ble.keys.counter);
832     }
833 }
834
835 /*******************************************************************************
836 **
837 ** Function         btm_ble_get_enc_key_type
838 **
839 ** Description      This function is to get the BLE key type that has been exchanged
840 **                  in betweem local device and peer device.
841 **
842 ** Returns          p_key_type: output parameter to carry the key type value.
843 **
844 *******************************************************************************/
845 BOOLEAN btm_ble_get_enc_key_type(BD_ADDR bd_addr, UINT8 *p_key_types)
846 {
847     tBTM_SEC_DEV_REC *p_dev_rec;
848
849     BTM_TRACE_DEBUG ("btm_ble_get_enc_key_type");
850
851     if ((p_dev_rec = btm_find_dev (bd_addr)) != NULL)
852     {
853         *p_key_types = p_dev_rec->ble.key_type;
854         return TRUE;
855     }
856     return FALSE;
857 }
858
859 /*******************************************************************************
860 **
861 ** Function         btm_get_local_div
862 **
863 ** Description      This function is called to read the local DIV
864 **
865 ** Returns          TURE - if a valid DIV is availavle
866 *******************************************************************************/
867 BOOLEAN btm_get_local_div (BD_ADDR bd_addr, UINT16 *p_div)
868 {
869     tBTM_SEC_DEV_REC   *p_dev_rec;
870     BOOLEAN            status = FALSE;
871     BTM_TRACE_DEBUG ("btm_get_local_div");
872
873     BTM_TRACE_DEBUG("bd_addr:%02x-%02x-%02x-%02x-%02x-%02x",
874                      bd_addr[0],bd_addr[1],
875                      bd_addr[2],bd_addr[3],
876                      bd_addr[4],bd_addr[5]);
877
878     *p_div = 0;
879     p_dev_rec = btm_find_dev (bd_addr);
880
881     if (p_dev_rec && p_dev_rec->ble.keys.div)
882     {
883         status = TRUE;
884         *p_div = p_dev_rec->ble.keys.div;
885     }
886     BTM_TRACE_DEBUG ("btm_get_local_div status=%d (1-OK) DIV=0x%x", status, *p_div);
887     return status;
888 }
889
890 /*******************************************************************************
891 **
892 ** Function         btm_sec_save_le_key
893 **
894 ** Description      This function is called by the SMP to update
895 **                  an  BLE key.  SMP is internal, whereas all the keys shall
896 **                  be sent to the application.  The function is also called
897 **                  when application passes ble key stored in NVRAM to the btm_sec.
898 **                  pass_to_application parameter is false in this case.
899 **
900 ** Returns          void
901 **
902 *******************************************************************************/
903 void btm_sec_save_le_key(BD_ADDR bd_addr, tBTM_LE_KEY_TYPE key_type, tBTM_LE_KEY_VALUE *p_keys,
904                          BOOLEAN pass_to_application)
905 {
906     tBTM_SEC_DEV_REC *p_rec;
907     tBTM_LE_EVT_DATA    cb_data;
908     UINT8 i;
909
910     BTM_TRACE_DEBUG ("btm_sec_save_le_key key_type=0x%x pass_to_application=%d",key_type, pass_to_application);
911     /* Store the updated key in the device database */
912
913     BTM_TRACE_DEBUG("bd_addr:%02x-%02x-%02x-%02x-%02x-%02x",
914                      bd_addr[0],bd_addr[1],
915                      bd_addr[2],bd_addr[3],
916                      bd_addr[4],bd_addr[5]);
917
918     if ((p_rec = btm_find_dev (bd_addr)) != NULL && (p_keys || key_type== BTM_LE_KEY_LID))
919     {
920         switch (key_type)
921         {
922             case BTM_LE_KEY_PENC:
923                 memcpy(p_rec->ble.keys.pltk, p_keys->penc_key.ltk, BT_OCTET16_LEN);
924                 memcpy(p_rec->ble.keys.rand, p_keys->penc_key.rand, BT_OCTET8_LEN);
925                 p_rec->ble.keys.sec_level = p_keys->penc_key.sec_level;
926                 p_rec->ble.keys.ediv = p_keys->penc_key.ediv;
927                 p_rec->ble.keys.key_size = p_keys->penc_key.key_size;
928                 p_rec->ble.key_type |= BTM_LE_KEY_PENC;
929                 p_rec->sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN;
930                 if (p_keys->penc_key.sec_level == SMP_SEC_AUTHENTICATED)
931                     p_rec->sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED;
932                 else
933                     p_rec->sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED;
934                 BTM_TRACE_DEBUG("BTM_LE_KEY_PENC key_type=0x%x sec_flags=0x%x sec_leve=0x%x",
935                                  p_rec->ble.key_type,
936                                  p_rec->sec_flags,
937                                  p_rec->ble.keys.sec_level);
938                 break;
939
940             case BTM_LE_KEY_PID:
941                 for (i=0; i<BT_OCTET16_LEN; i++)
942                 {
943                     p_rec->ble.keys.irk[i] = p_keys->pid_key.irk[i];
944                 }
945
946                  //memcpy( p_rec->ble.keys.irk, p_keys->pid_key, BT_OCTET16_LEN); todo will crash the system
947                 memcpy(p_rec->ble.static_addr, p_keys->pid_key.static_addr, BD_ADDR_LEN);
948                 p_rec->ble.static_addr_type = p_keys->pid_key.addr_type;
949                 p_rec->ble.key_type |= BTM_LE_KEY_PID;
950                 BTM_TRACE_DEBUG("BTM_LE_KEY_PID key_type=0x%x save peer IRK",  p_rec->ble.key_type);
951                 break;
952
953             case BTM_LE_KEY_PCSRK:
954                 memcpy(p_rec->ble.keys.pcsrk, p_keys->pcsrk_key.csrk, BT_OCTET16_LEN);
955                 p_rec->ble.keys.srk_sec_level = p_keys->pcsrk_key.sec_level;
956                 p_rec->ble.keys.counter  = p_keys->pcsrk_key.counter;
957                 p_rec->ble.key_type |= BTM_LE_KEY_PCSRK;
958                 p_rec->sec_flags |=  BTM_SEC_LE_LINK_KEY_KNOWN;
959                 if ( p_keys->pcsrk_key.sec_level== SMP_SEC_AUTHENTICATED)
960                     p_rec->sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED;
961                 else
962                     p_rec->sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED;
963
964                 BTM_TRACE_DEBUG("BTM_LE_KEY_PCSRK key_type=0x%x sec_flags=0x%x sec_level=0x%x peer_counter=%d",
965                                  p_rec->ble.key_type,
966                                  p_rec->sec_flags,
967                                  p_rec->ble.keys.srk_sec_level,
968                                  p_rec->ble.keys.counter );
969                 break;
970
971             case BTM_LE_KEY_LENC:
972                 memcpy(p_rec->ble.keys.lltk, p_keys->lenc_key.ltk, BT_OCTET16_LEN);
973                 p_rec->ble.keys.div = p_keys->lenc_key.div; /* update DIV */
974                 p_rec->ble.keys.sec_level = p_keys->lenc_key.sec_level;
975                 p_rec->ble.keys.key_size = p_keys->lenc_key.key_size;
976                 p_rec->ble.key_type |= BTM_LE_KEY_LENC;
977
978                 BTM_TRACE_DEBUG("BTM_LE_KEY_LENC key_type=0x%x DIV=0x%x key_size=0x%x sec_level=0x%x",
979                                  p_rec->ble.key_type,
980                                  p_rec->ble.keys.div,
981                                  p_rec->ble.keys.key_size,
982                                  p_rec->ble.keys.sec_level );
983                 break;
984
985             case BTM_LE_KEY_LCSRK:/* local CSRK has been delivered */
986                 memcpy (p_rec->ble.keys.lcsrk, p_keys->lcsrk_key.csrk, BT_OCTET16_LEN);
987                 p_rec->ble.keys.div = p_keys->lcsrk_key.div; /* update DIV */
988                 p_rec->ble.keys.local_csrk_sec_level = p_keys->lcsrk_key.sec_level;
989                 p_rec->ble.keys.local_counter  = p_keys->lcsrk_key.counter;
990                 p_rec->ble.key_type |= BTM_LE_KEY_LCSRK;
991                 BTM_TRACE_DEBUG("BTM_LE_KEY_LCSRK key_type=0x%x DIV=0x%x scrk_sec_level=0x%x local_counter=%d",
992                                  p_rec->ble.key_type,
993                                  p_rec->ble.keys.div,
994                                  p_rec->ble.keys.local_csrk_sec_level,
995                                  p_rec->ble.keys.local_counter );
996                 break;
997
998             case BTM_LE_KEY_LID:
999                p_rec->ble.key_type |= BTM_LE_KEY_LID;
1000                break;
1001             default:
1002                 BTM_TRACE_WARNING("btm_sec_save_le_key (Bad key_type 0x%02x)", key_type);
1003                 return;
1004         }
1005
1006         BTM_TRACE_DEBUG ("BLE key type 0x%02x updated for BDA: %08x%04x (btm_sec_save_le_key)", key_type,
1007                           (bd_addr[0]<<24)+(bd_addr[1]<<16)+(bd_addr[2]<<8)+bd_addr[3],
1008                           (bd_addr[4]<<8)+bd_addr[5]);
1009
1010         /* Notify the application that one of the BLE keys has been updated
1011            If link key is in progress, it will get sent later.*/
1012         if (pass_to_application && btm_cb.api.p_le_callback)
1013         {
1014             cb_data.key.p_key_value = p_keys;
1015             cb_data.key.key_type = key_type;
1016
1017             (*btm_cb.api.p_le_callback) (BTM_LE_KEY_EVT, bd_addr, &cb_data);
1018         }
1019         return;
1020     }
1021
1022     BTM_TRACE_WARNING ("BLE key type 0x%02x called for Unknown BDA or type: %08x%04x !! (btm_sec_save_le_key)", key_type,
1023                         (bd_addr[0]<<24)+(bd_addr[1]<<16)+(bd_addr[2]<<8)+bd_addr[3],
1024                         (bd_addr[4]<<8)+bd_addr[5]);
1025
1026     if (p_rec)
1027     {
1028         BTM_TRACE_DEBUG ("sec_flags=0x%x", p_rec->sec_flags);
1029     }
1030 }
1031
1032 /*******************************************************************************
1033 **
1034 ** Function         btm_ble_update_sec_key_size
1035 **
1036 ** Description      update the current lin kencryption key size
1037 **
1038 ** Returns          void
1039 **
1040 *******************************************************************************/
1041 void btm_ble_update_sec_key_size(BD_ADDR bd_addr, UINT8 enc_key_size)
1042 {
1043     tBTM_SEC_DEV_REC *p_rec;
1044
1045     BTM_TRACE_DEBUG("btm_ble_update_sec_key_size enc_key_size = %d", enc_key_size);
1046
1047     if ((p_rec = btm_find_dev (bd_addr)) != NULL )
1048     {
1049         p_rec->enc_key_size = enc_key_size;
1050     }
1051 }
1052
1053 /*******************************************************************************
1054 **
1055 ** Function         btm_ble_read_sec_key_size
1056 **
1057 ** Description      update the current lin kencryption key size
1058 **
1059 ** Returns          void
1060 **
1061 *******************************************************************************/
1062 UINT8 btm_ble_read_sec_key_size(BD_ADDR bd_addr)
1063 {
1064     tBTM_SEC_DEV_REC *p_rec;
1065
1066     if ((p_rec = btm_find_dev (bd_addr)) != NULL )
1067     {
1068         return p_rec->enc_key_size;
1069     }
1070     else
1071         return 0;
1072 }
1073
1074 /*******************************************************************************
1075 **
1076 ** Function         btm_ble_link_sec_check
1077 **
1078 ** Description      Check BLE link security level match.
1079 **
1080 ** Returns          TRUE: check is OK and the *p_sec_req_act contain the action
1081 **
1082 *******************************************************************************/
1083 void btm_ble_link_sec_check(BD_ADDR bd_addr, tBTM_LE_AUTH_REQ auth_req, tBTM_BLE_SEC_REQ_ACT *p_sec_req_act)
1084 {
1085     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bd_addr);
1086     UINT8 req_sec_level = BTM_LE_SEC_NONE, cur_sec_level = BTM_LE_SEC_NONE;
1087
1088     BTM_TRACE_DEBUG ("btm_ble_link_sec_check auth_req =0x%x", auth_req);
1089
1090     if (p_dev_rec == NULL)
1091     {
1092         BTM_TRACE_ERROR ("btm_ble_link_sec_check received for unknown device");
1093         return;
1094     }
1095
1096     if (p_dev_rec->sec_state == BTM_SEC_STATE_ENCRYPTING ||
1097         p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING)
1098     {
1099         /* race condition: discard the security request while master is encrypting the link */
1100         *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_DISCARD;
1101     }
1102     else
1103     {
1104         req_sec_level = BTM_LE_SEC_UNAUTHENTICATE;
1105         if (auth_req & BTM_LE_AUTH_REQ_MITM)
1106         {
1107             req_sec_level = BTM_LE_SEC_AUTHENTICATED;
1108         }
1109
1110         BTM_TRACE_DEBUG ("dev_rec sec_flags=0x%x", p_dev_rec->sec_flags);
1111
1112         /* currently encrpted  */
1113         if (p_dev_rec->sec_flags & BTM_SEC_LE_ENCRYPTED)
1114         {
1115             if (p_dev_rec->sec_flags & BTM_SEC_LE_AUTHENTICATED)
1116                 cur_sec_level = BTM_LE_SEC_AUTHENTICATED;
1117             else
1118                 cur_sec_level = BTM_LE_SEC_UNAUTHENTICATE;
1119         }
1120         else /* unencrypted link */
1121         {
1122             /* if bonded, get the key security level */
1123             if (p_dev_rec->ble.key_type & BTM_LE_KEY_PENC)
1124                 cur_sec_level = p_dev_rec->ble.keys.sec_level;
1125             else
1126                 cur_sec_level = BTM_LE_SEC_NONE;
1127         }
1128
1129         if (cur_sec_level >= req_sec_level)
1130         {
1131             /* To avoid re-encryption on an encrypted link for an equal condition encryption */
1132             *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_ENCRYPT;
1133         }
1134         else
1135         {
1136             *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_PAIR; /* start the pariring process to upgrade the keys*/
1137         }
1138     }
1139
1140     BTM_TRACE_DEBUG("cur_sec_level=%d req_sec_level=%d sec_req_act=%d",
1141                      cur_sec_level,
1142                      req_sec_level,
1143                      *p_sec_req_act);
1144
1145 }
1146
1147 /*******************************************************************************
1148 **
1149 ** Function         btm_ble_set_encryption
1150 **
1151 ** Description      This function is called to ensure that LE connection is
1152 **                  encrypted.  Should be called only on an open connection.
1153 **                  Typically only needed for connections that first want to
1154 **                  bring up unencrypted links, then later encrypt them.
1155 **
1156 ** Returns          void
1157 **                  the local device ER is copied into er
1158 **
1159 *******************************************************************************/
1160 tBTM_STATUS btm_ble_set_encryption (BD_ADDR bd_addr, void *p_ref_data, UINT8 link_role)
1161 {
1162     tBTM_STATUS         cmd = BTM_NO_RESOURCES;
1163     tBTM_BLE_SEC_ACT    sec_act = *(tBTM_BLE_SEC_ACT *)p_ref_data ;
1164     tBTM_SEC_DEV_REC    *p_rec = btm_find_dev (bd_addr);
1165     tBTM_BLE_SEC_REQ_ACT sec_req_act;
1166     tBTM_LE_AUTH_REQ    auth_req;
1167
1168     if (p_rec == NULL)
1169     {
1170         BTM_TRACE_WARNING ("btm_ble_set_encryption (NULL device record!! sec_act=0x%x", sec_act);
1171         return(BTM_WRONG_MODE);
1172     }
1173
1174     BTM_TRACE_DEBUG ("btm_ble_set_encryption sec_act=0x%x role_master=%d", sec_act, p_rec->role_master);
1175
1176     if (sec_act == BTM_BLE_SEC_ENCRYPT_MITM)
1177     {
1178         p_rec->security_required |= BTM_SEC_IN_MITM;
1179     }
1180
1181     switch (sec_act)
1182     {
1183         case BTM_BLE_SEC_ENCRYPT:
1184             if (link_role == BTM_ROLE_MASTER)
1185             {
1186                     /* start link layer encryption using the security info stored */
1187                 cmd = btm_ble_start_encrypt(bd_addr, FALSE, NULL);
1188                 break;
1189             }
1190             /* if salve role then fall through to call SMP_Pair below which will send a
1191                sec_request to request the master to encrypt the link */
1192         case BTM_BLE_SEC_ENCRYPT_NO_MITM:
1193         case BTM_BLE_SEC_ENCRYPT_MITM:
1194             if (link_role == BTM_ROLE_MASTER)
1195             {
1196                 auth_req = (sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM)
1197                            ? SMP_AUTH_GEN_BOND : (SMP_AUTH_GEN_BOND | SMP_AUTH_YN_BIT);
1198                 btm_ble_link_sec_check (bd_addr, auth_req, &sec_req_act);
1199
1200                 if (sec_req_act == BTM_BLE_SEC_REQ_ACT_ENCRYPT)
1201                 {
1202                    cmd = btm_ble_start_encrypt(bd_addr, FALSE, NULL);
1203                    break;
1204                 }
1205             }
1206
1207             if (SMP_Pair(bd_addr) == SMP_STARTED)
1208             {
1209                 cmd = BTM_CMD_STARTED;
1210                 p_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
1211             }
1212             break;
1213
1214         default:
1215             cmd = BTM_WRONG_MODE;
1216             break;
1217     }
1218     return cmd;
1219 }
1220
1221 /*******************************************************************************
1222 **
1223 ** Function         btm_ble_ltk_request
1224 **
1225 ** Description      This function is called when encryption request is received
1226 **                  on a slave device.
1227 **
1228 **
1229 ** Returns          void
1230 **
1231 *******************************************************************************/
1232 void btm_ble_ltk_request(UINT16 handle, UINT8 rand[8], UINT16 ediv)
1233 {
1234     tBTM_CB *p_cb = &btm_cb;
1235     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev_by_handle (handle);
1236     BT_OCTET8 dummy_stk = {0};
1237
1238     BTM_TRACE_DEBUG ("btm_ble_ltk_request");
1239
1240     p_cb->ediv = ediv;
1241
1242     memcpy(p_cb->enc_rand, rand, BT_OCTET8_LEN);
1243
1244     if (p_dev_rec != NULL)
1245     {
1246         if (!smp_proc_ltk_request(p_dev_rec->bd_addr))
1247             btm_ble_ltk_request_reply(p_dev_rec->bd_addr, FALSE, dummy_stk);
1248     }
1249
1250 }
1251
1252 /*******************************************************************************
1253 **
1254 ** Function         btm_ble_start_encrypt
1255 **
1256 ** Description      This function is called to start LE encryption.
1257 **
1258 **
1259 ** Returns          BTM_SUCCESS if encryption was started successfully
1260 **
1261 *******************************************************************************/
1262 tBTM_STATUS btm_ble_start_encrypt(BD_ADDR bda, BOOLEAN use_stk, BT_OCTET16 stk)
1263 {
1264     tBTM_CB *p_cb = &btm_cb;
1265     tBTM_SEC_DEV_REC    *p_rec = btm_find_dev (bda);
1266     BT_OCTET8    dummy_rand = {0};
1267     tBTM_STATUS  rt = BTM_NO_RESOURCES;
1268
1269     BTM_TRACE_DEBUG ("btm_ble_start_encrypt");
1270
1271     if (!p_rec )
1272     {
1273         BTM_TRACE_ERROR("Link is not active, can not encrypt!");
1274         return BTM_WRONG_MODE;
1275     }
1276
1277     if (p_rec->sec_state == BTM_SEC_STATE_ENCRYPTING)
1278     {
1279         BTM_TRACE_WARNING("Link Encryption is active, Busy!");
1280         return BTM_BUSY;
1281     }
1282
1283     p_cb->enc_handle = p_rec->ble_hci_handle;
1284
1285     if (use_stk)
1286     {
1287         if (btsnd_hcic_ble_start_enc(p_rec->ble_hci_handle, dummy_rand, 0, stk))
1288             rt = BTM_CMD_STARTED;
1289     }
1290     else if (p_rec->ble.key_type & BTM_LE_KEY_PENC)
1291     {
1292         if (btsnd_hcic_ble_start_enc(p_rec->ble_hci_handle, p_rec->ble.keys.rand,
1293                                      p_rec->ble.keys.ediv, p_rec->ble.keys.pltk))
1294             rt = BTM_CMD_STARTED;
1295     }
1296     else
1297     {
1298         BTM_TRACE_ERROR("No key available to encrypt the link");
1299     }
1300     if (rt == BTM_CMD_STARTED)
1301     {
1302         if (p_rec->sec_state == BTM_SEC_STATE_IDLE)
1303             p_rec->sec_state = BTM_SEC_STATE_ENCRYPTING;
1304     }
1305
1306     return rt;
1307 }
1308
1309 /*******************************************************************************
1310 **
1311 ** Function         btm_ble_link_encrypted
1312 **
1313 ** Description      This function is called when LE link encrption status is changed.
1314 **
1315 ** Returns          void
1316 **
1317 *******************************************************************************/
1318 void btm_ble_link_encrypted(BD_ADDR bd_addr, UINT8 encr_enable)
1319 {
1320     tBTM_SEC_DEV_REC    *p_dev_rec = btm_find_dev (bd_addr);
1321     BOOLEAN             enc_cback;
1322
1323     if (!p_dev_rec)
1324     {
1325         BTM_TRACE_WARNING ("btm_ble_link_encrypted (No Device Found!) encr_enable=%d", encr_enable);
1326         return;
1327     }
1328
1329     BTM_TRACE_DEBUG ("btm_ble_link_encrypted encr_enable=%d", encr_enable);
1330
1331     enc_cback = (p_dev_rec->sec_state == BTM_SEC_STATE_ENCRYPTING);
1332
1333     smp_link_encrypted(bd_addr, encr_enable);
1334
1335     BTM_TRACE_DEBUG(" p_dev_rec->sec_flags=0x%x", p_dev_rec->sec_flags);
1336
1337     if (encr_enable && p_dev_rec->enc_key_size == 0)
1338         p_dev_rec->enc_key_size = p_dev_rec->ble.keys.key_size;
1339
1340     p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
1341     if (p_dev_rec->p_callback && enc_cback)
1342     {
1343         if (encr_enable)
1344             btm_sec_dev_rec_cback_event(p_dev_rec, BTM_SUCCESS, TRUE);
1345         else if (p_dev_rec->role_master)
1346             btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, TRUE);
1347
1348     }
1349     /* to notify GATT to send data if any request is pending */
1350     gatt_notify_enc_cmpl(p_dev_rec->bd_addr);
1351 }
1352
1353 /*******************************************************************************
1354 ** Function         btm_enc_proc_ltk
1355 ** Description      send LTK reply when it's ready.
1356 *******************************************************************************/
1357 static void btm_enc_proc_ltk(tSMP_ENC *p)
1358 {
1359     UINT8   i;
1360     BTM_TRACE_DEBUG ("btm_enc_proc_ltk");
1361     if (p && p->param_len == BT_OCTET16_LEN)
1362     {
1363         for (i = 0; i < (BT_OCTET16_LEN - btm_cb.key_size); i ++)
1364             p->param_buf[BT_OCTET16_LEN - i - 1] = 0;
1365         btsnd_hcic_ble_ltk_req_reply(btm_cb.enc_handle, p->param_buf);
1366     }
1367 }
1368
1369 /*******************************************************************************
1370 ** Function         btm_enc_proc_slave_y
1371 ** Description      calculate LTK when Y is ready
1372 *******************************************************************************/
1373 static void btm_enc_proc_slave_y(tSMP_ENC *p)
1374 {
1375     UINT16  div, y;
1376     UINT8   *pp = p->param_buf;
1377     tBTM_CB *p_cb = &btm_cb;
1378     tSMP_ENC output;
1379     tBTM_SEC_DEV_REC *p_dev_rec;
1380
1381     BTM_TRACE_DEBUG ("btm_enc_proc_slave_y");
1382     if (p != NULL)
1383     {
1384         STREAM_TO_UINT16(y, pp);
1385
1386         div = p_cb->ediv ^ y;
1387         p_dev_rec = btm_find_dev_by_handle (p_cb->enc_handle);
1388
1389         if ( p_dev_rec &&
1390              p_dev_rec->ble.keys.div == div )
1391         {
1392             BTM_TRACE_DEBUG ("LTK request OK");
1393             /* calculating LTK , LTK = E er(div) */
1394             SMP_Encrypt(p_cb->devcb.ble_encryption_key_value, BT_OCTET16_LEN, (UINT8 *)&div, 2, &output);
1395             btm_enc_proc_ltk(&output);
1396         }
1397         else
1398         {
1399             BTM_TRACE_DEBUG ("LTK request failed - send negative reply");
1400             btsnd_hcic_ble_ltk_req_neg_reply(p_cb->enc_handle);
1401             if (p_dev_rec)
1402                 btm_ble_link_encrypted(p_dev_rec->bd_addr, 0);
1403
1404         }
1405     }
1406 }
1407
1408 /*******************************************************************************
1409 **
1410 ** Function         btm_ble_ltk_request_reply
1411 **
1412 ** Description      This function is called to send a LTK request reply on a slave
1413 **                  device.
1414 **
1415 ** Returns          void
1416 **
1417 *******************************************************************************/
1418 void btm_ble_ltk_request_reply(BD_ADDR bda,  BOOLEAN use_stk, BT_OCTET16 stk)
1419 {
1420     tBTM_SEC_DEV_REC    *p_rec = btm_find_dev (bda);
1421     tBTM_CB *p_cb = &btm_cb;
1422     tSMP_ENC output;
1423
1424     if (p_rec == NULL)
1425     {
1426         BTM_TRACE_ERROR("btm_ble_ltk_request_reply received for unknown device");
1427         return;
1428     }
1429
1430     BTM_TRACE_DEBUG ("btm_ble_ltk_request_reply");
1431     p_cb->enc_handle = p_rec->ble_hci_handle;
1432     p_cb->key_size = p_rec->ble.keys.key_size;
1433
1434     BTM_TRACE_ERROR("key size = %d", p_rec->ble.keys.key_size);
1435     if (use_stk)
1436     {
1437         btsnd_hcic_ble_ltk_req_reply(btm_cb.enc_handle, stk);
1438     }
1439     else /* calculate LTK using peer device  */
1440     {
1441         if (p_rec->ble.key_type & BTM_LE_KEY_LENC)
1442             btsnd_hcic_ble_ltk_req_reply(btm_cb.enc_handle, p_rec->ble.keys.lltk);
1443         else
1444             btsnd_hcic_ble_ltk_req_neg_reply(btm_cb.enc_handle);
1445     }
1446 }
1447
1448 /*******************************************************************************
1449 **
1450 ** Function         btm_ble_io_capabilities_req
1451 **
1452 ** Description      This function is called to handle SMP get IO capability request.
1453 **
1454 ** Returns          void
1455 **
1456 *******************************************************************************/
1457 UINT8 btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC *p_dev_rec, tBTM_LE_IO_REQ *p_data)
1458 {
1459     UINT8           callback_rc = BTM_SUCCESS;
1460     BTM_TRACE_DEBUG ("btm_ble_io_capabilities_req");
1461     if (btm_cb.api.p_le_callback)
1462     {
1463         /* the callback function implementation may change the IO capability... */
1464         callback_rc = (*btm_cb.api.p_le_callback) (BTM_LE_IO_REQ_EVT, p_dev_rec->bd_addr, (tBTM_LE_EVT_DATA *)p_data);
1465     }
1466 #if BTM_OOB_INCLUDED == TRUE
1467     if ((callback_rc == BTM_SUCCESS) || (BTM_OOB_UNKNOWN != p_data->oob_data))
1468 #else
1469     if (callback_rc == BTM_SUCCESS)
1470 #endif
1471     {
1472 #if BTM_BLE_CONFORMANCE_TESTING == TRUE
1473         if (btm_cb.devcb.keep_rfu_in_auth_req)
1474         {
1475             BTM_TRACE_DEBUG ("btm_ble_io_capabilities_req keep_rfu_in_auth_req = %u",
1476                 btm_cb.devcb.keep_rfu_in_auth_req);
1477             p_data->auth_req &= BTM_LE_AUTH_REQ_MASK_KEEP_RFU;
1478             btm_cb.devcb.keep_rfu_in_auth_req = FALSE;
1479         }
1480         else
1481         {   /* default */
1482             p_data->auth_req &= BTM_LE_AUTH_REQ_MASK;
1483         }
1484 #else
1485         p_data->auth_req &= BTM_LE_AUTH_REQ_MASK;
1486 #endif
1487
1488         BTM_TRACE_DEBUG ("btm_ble_io_capabilities_req 1: p_dev_rec->security_required = %d auth_req:%d",
1489                           p_dev_rec->security_required, p_data->auth_req);
1490         BTM_TRACE_DEBUG ("btm_ble_io_capabilities_req 2: i_keys=0x%x r_keys=0x%x (bit 0-LTK 1-IRK 2-CSRK)",
1491                           p_data->init_keys,
1492                           p_data->resp_keys);
1493
1494         /* if authentication requires MITM protection, put on the mask */
1495         if (p_dev_rec->security_required & BTM_SEC_IN_MITM)
1496             p_data->auth_req |= BTM_LE_AUTH_REQ_MITM;
1497
1498         if (!(p_data->auth_req & SMP_AUTH_BOND))
1499         {
1500             BTM_TRACE_DEBUG("Non bonding: No keys should be exchanged");
1501             p_data->init_keys = 0;
1502             p_data->resp_keys = 0;
1503         }
1504
1505         BTM_TRACE_DEBUG ("btm_ble_io_capabilities_req 3: auth_req:%d", p_data->auth_req);
1506         BTM_TRACE_DEBUG ("btm_ble_io_capabilities_req 4: i_keys=0x%x r_keys=0x%x",
1507                           p_data->init_keys,
1508                           p_data->resp_keys);
1509
1510         BTM_TRACE_DEBUG ("btm_ble_io_capabilities_req 5: p_data->io_cap = %d auth_req:%d",
1511                           p_data->io_cap, p_data->auth_req);
1512
1513         /* remove MITM protection requirement if IO cap does not allow it */
1514         if ((p_data->io_cap == BTM_IO_CAP_NONE) && p_data->oob_data == SMP_OOB_NONE)
1515             p_data->auth_req &= ~BTM_LE_AUTH_REQ_MITM;
1516
1517         if (!(p_data->auth_req & SMP_SC_SUPPORT_BIT))
1518         {
1519             /* if Secure Connections are not supported then remove LK derivation,
1520             ** and keypress notifications.
1521             */
1522             BTM_TRACE_DEBUG("%s-SC not supported -> No LK derivation, no keypress notifications",
1523                             __func__);
1524             p_data->auth_req &= ~SMP_KP_SUPPORT_BIT;
1525             p_data->init_keys &= ~SMP_SEC_KEY_TYPE_LK;
1526             p_data->resp_keys &= ~SMP_SEC_KEY_TYPE_LK;
1527         }
1528
1529         BTM_TRACE_DEBUG ("btm_ble_io_capabilities_req 6: IO_CAP:%d oob_data:%d auth_req:0x%02x",
1530                           p_data->io_cap, p_data->oob_data, p_data->auth_req);
1531     }
1532     return callback_rc;
1533 }
1534
1535 /*******************************************************************************
1536 **
1537 ** Function         btm_ble_br_keys_req
1538 **
1539 ** Description      This function is called to handle SMP request for keys sent
1540 **                  over BR/EDR.
1541 **
1542 ** Returns          void
1543 **
1544 *******************************************************************************/
1545 UINT8 btm_ble_br_keys_req(tBTM_SEC_DEV_REC *p_dev_rec, tBTM_LE_IO_REQ *p_data)
1546 {
1547     UINT8           callback_rc = BTM_SUCCESS;
1548     BTM_TRACE_DEBUG ("%s", __func__);
1549     if (btm_cb.api.p_le_callback)
1550     {
1551         /* the callback function implementation may change the IO capability... */
1552         callback_rc = (*btm_cb.api.p_le_callback) (BTM_LE_IO_REQ_EVT, p_dev_rec->bd_addr,
1553                                                   (tBTM_LE_EVT_DATA *)p_data);
1554     }
1555
1556     return callback_rc;
1557 }
1558
1559 #if (BLE_PRIVACY_SPT == TRUE )
1560 /*******************************************************************************
1561 **
1562 ** Function         btm_ble_resolve_random_addr_on_conn_cmpl
1563 **
1564 ** Description      resolve random address complete on connection complete event.
1565 **
1566 ** Returns          void
1567 **
1568 *******************************************************************************/
1569 static void btm_ble_resolve_random_addr_on_conn_cmpl(void * p_rec, void *p_data)
1570 {
1571     UINT8   *p = (UINT8 *)p_data;
1572     tBTM_SEC_DEV_REC    *match_rec = (tBTM_SEC_DEV_REC *) p_rec;
1573     UINT8       role, bda_type;
1574     UINT16      handle;
1575     BD_ADDR     bda;
1576     UINT16      conn_interval, conn_latency, conn_timeout;
1577     BOOLEAN     match = FALSE;
1578
1579     ++p;
1580     STREAM_TO_UINT16   (handle, p);
1581     STREAM_TO_UINT8    (role, p);
1582     STREAM_TO_UINT8    (bda_type, p);
1583     STREAM_TO_BDADDR   (bda, p);
1584     STREAM_TO_UINT16   (conn_interval, p);
1585     STREAM_TO_UINT16   (conn_latency, p);
1586     STREAM_TO_UINT16   (conn_timeout, p);
1587
1588     handle = HCID_GET_HANDLE (handle);
1589
1590     BTM_TRACE_EVENT ("%s", __func__);
1591
1592     if (match_rec)
1593     {
1594         LOG_INFO("%s matched and resolved random address", __func__);
1595         match = TRUE;
1596         match_rec->ble.active_addr_type = BTM_BLE_ADDR_RRA;
1597         memcpy(match_rec->ble.cur_rand_addr, bda, BD_ADDR_LEN);
1598         memcpy(bda, match_rec->bd_addr, BD_ADDR_LEN);
1599     }
1600     else
1601     {
1602         LOG_INFO("%s unable to match and resolve random address", __func__);
1603     }
1604
1605     btm_ble_connected(bda, handle, HCI_ENCRYPT_MODE_DISABLED, role, bda_type, match);
1606
1607     l2cble_conn_comp (handle, role, bda, bda_type, conn_interval,
1608                       conn_latency, conn_timeout);
1609
1610     return;
1611 }
1612 #endif
1613
1614 /*******************************************************************************
1615 **
1616 ** Function         btm_ble_connected
1617 **
1618 ** Description      This function is when a LE connection to the peer device is
1619 **                  establsihed
1620 **
1621 ** Returns          void
1622 **
1623 *******************************************************************************/
1624 void btm_ble_connected (UINT8 *bda, UINT16 handle, UINT8 enc_mode, UINT8 role,
1625                         tBLE_ADDR_TYPE addr_type, BOOLEAN addr_matched)
1626 {
1627     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bda);
1628     tBTM_BLE_CB *p_cb = &btm_cb.ble_ctr_cb;
1629     UNUSED(addr_matched);
1630
1631     BTM_TRACE_EVENT ("btm_ble_connected");
1632
1633     /* Commenting out trace due to obf/compilation problems.
1634     */
1635 #if (BT_USE_TRACES == TRUE)
1636     if (p_dev_rec)
1637     {
1638         BTM_TRACE_EVENT ("Security Manager: btm_ble_connected :  handle:%d  enc_mode:%d  bda:%x RName:%s",
1639                           handle,  enc_mode,
1640                           (bda[2]<<24)+(bda[3]<<16)+(bda[4]<<8)+bda[5],
1641                           p_dev_rec->sec_bd_name);
1642
1643         BTM_TRACE_DEBUG ("btm_ble_connected sec_flags=0x%x",p_dev_rec->sec_flags);
1644     }
1645     else
1646     {
1647         BTM_TRACE_EVENT ("Security Manager: btm_ble_connected:   handle:%d  enc_mode:%d  bda:%x ",
1648                           handle,  enc_mode,
1649                           (bda[2]<<24)+(bda[3]<<16)+(bda[4]<<8)+bda[5]);
1650     }
1651 #endif
1652
1653     if (!p_dev_rec)
1654     {
1655         /* There is no device record for new connection.  Allocate one */
1656         p_dev_rec = btm_sec_alloc_dev (bda);
1657     }
1658     else    /* Update the timestamp for this device */
1659     {
1660         p_dev_rec->timestamp = btm_cb.dev_rec_count++;
1661     }
1662
1663     /* update device information */
1664     p_dev_rec->device_type |= BT_DEVICE_TYPE_BLE;
1665     p_dev_rec->ble_hci_handle = handle;
1666     p_dev_rec->ble.ble_addr_type = addr_type;
1667
1668     p_dev_rec->role_master = FALSE;
1669     if (role == HCI_ROLE_MASTER)
1670         p_dev_rec->role_master = TRUE;
1671
1672 #if (defined BLE_PRIVACY_SPT && BLE_PRIVACY_SPT == TRUE)
1673     if (!addr_matched)
1674         p_dev_rec->ble.active_addr_type = BTM_BLE_ADDR_PSEUDO;
1675
1676     if (p_dev_rec->ble.ble_addr_type == BLE_ADDR_RANDOM && !addr_matched)
1677         memcpy(p_dev_rec->ble.cur_rand_addr, bda, BD_ADDR_LEN);
1678 #endif
1679
1680     p_cb->inq_var.directed_conn = BTM_BLE_CONNECT_EVT;
1681
1682     return;
1683 }
1684
1685 /*****************************************************************************
1686 **  Function        btm_ble_conn_complete
1687 **
1688 **  Description     LE connection complete.
1689 **
1690 ******************************************************************************/
1691 void btm_ble_conn_complete(UINT8 *p, UINT16 evt_len, BOOLEAN enhanced)
1692 {
1693 #if (BLE_PRIVACY_SPT == TRUE )
1694     UINT8       *p_data = p;
1695 #endif
1696     UINT8       role, status, bda_type, peer_addr_type;
1697     UINT16      handle;
1698     BD_ADDR     bda, local_rpa, peer_rpa;
1699     UINT16      conn_interval, conn_latency, conn_timeout;
1700     BOOLEAN     match = FALSE;
1701     UNUSED(evt_len);
1702
1703     STREAM_TO_UINT8   (status, p);
1704     STREAM_TO_UINT16   (handle, p);
1705     STREAM_TO_UINT8    (role, p);
1706     STREAM_TO_UINT8    (bda_type, p);
1707     peer_addr_type = bda_type ;
1708     STREAM_TO_BDADDR   (bda, p);
1709
1710     if (status == 0)
1711     {
1712 #if (BLE_PRIVACY_SPT == TRUE )
1713         match = btm_identity_addr_to_random_pseudo (bda, &bda_type, TRUE);
1714
1715         if (enhanced)
1716         {
1717             STREAM_TO_BDADDR   (local_rpa, p);
1718             STREAM_TO_BDADDR   (peer_rpa, p);
1719         }
1720
1721         /* possiblly receive connection complete with resolvable random on
1722            slave role while the device has been paired */
1723         if (!match && role == HCI_ROLE_SLAVE && BTM_BLE_IS_RESOLVE_BDA(bda))
1724         {
1725             btm_ble_resolve_random_addr(bda, btm_ble_resolve_random_addr_on_conn_cmpl, p_data);
1726         }
1727         else
1728 #endif
1729         {
1730             STREAM_TO_UINT16   (conn_interval, p);
1731             STREAM_TO_UINT16   (conn_latency, p);
1732             STREAM_TO_UINT16   (conn_timeout, p);
1733             handle = HCID_GET_HANDLE (handle);
1734
1735             btm_ble_connected(bda, handle, HCI_ENCRYPT_MODE_DISABLED, role, bda_type, match);
1736
1737             l2cble_conn_comp (handle, role, bda, bda_type, conn_interval,
1738                               conn_latency, conn_timeout);
1739
1740 #if (BLE_PRIVACY_SPT == TRUE)
1741             if (enhanced)
1742             {
1743                 btm_ble_refresh_local_resolvable_private_addr(bda, local_rpa);
1744
1745                 if (peer_addr_type & BLE_ADDR_TYPE_ID_BIT)
1746                     btm_ble_refresh_peer_resolvable_private_addr(bda, peer_rpa, BLE_ADDR_RANDOM);
1747             }
1748 #endif
1749         }
1750     }
1751     else
1752     {
1753         role = HCI_ROLE_UNKNOWN;
1754
1755         if (status != HCI_ERR_DIRECTED_ADVERTISING_TIMEOUT)
1756             btm_ble_set_conn_st(BLE_CONN_IDLE);
1757         }
1758
1759     btm_ble_update_mode_operation(role, bda, status);
1760 }
1761
1762
1763
1764 /*****************************************************************************
1765 ** Function btm_ble_create_ll_conn_complete
1766 **
1767 ** Description LE connection complete.
1768 **
1769 ******************************************************************************/
1770 void btm_ble_create_ll_conn_complete (UINT8 status)
1771 {
1772     if (status != HCI_SUCCESS)
1773     {
1774         btm_ble_set_conn_st(BLE_CONN_IDLE);
1775         btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, NULL, status);
1776     }
1777 }
1778 /*****************************************************************************
1779 **  Function        btm_proc_smp_cback
1780 **
1781 **  Description     This function is the SMP callback handler.
1782 **
1783 ******************************************************************************/
1784 UINT8 btm_proc_smp_cback(tSMP_EVT event, BD_ADDR bd_addr, tSMP_EVT_DATA *p_data)
1785 {
1786     tBTM_SEC_DEV_REC    *p_dev_rec = btm_find_dev (bd_addr);
1787     UINT8 res = 0;
1788
1789     BTM_TRACE_DEBUG ("btm_proc_smp_cback event = %d", event);
1790
1791     if (p_dev_rec != NULL)
1792     {
1793         switch (event)
1794         {
1795             case SMP_IO_CAP_REQ_EVT:
1796                 btm_ble_io_capabilities_req(p_dev_rec, (tBTM_LE_IO_REQ *)&p_data->io_req);
1797                 break;
1798
1799             case SMP_BR_KEYS_REQ_EVT:
1800                 btm_ble_br_keys_req(p_dev_rec, (tBTM_LE_IO_REQ *)&p_data->io_req);
1801                 break;
1802
1803             case SMP_PASSKEY_REQ_EVT:
1804             case SMP_PASSKEY_NOTIF_EVT:
1805             case SMP_OOB_REQ_EVT:
1806             case SMP_NC_REQ_EVT:
1807             case SMP_SC_OOB_REQ_EVT:
1808                 /* fall through */
1809                 p_dev_rec->sec_flags |= BTM_SEC_LE_AUTHENTICATED;
1810
1811             case SMP_SEC_REQUEST_EVT:
1812                 if (event == SMP_SEC_REQUEST_EVT && btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
1813                 {
1814                     BTM_TRACE_DEBUG("%s: Ignoring SMP Security request", __func__);
1815                     break;
1816                 }
1817                 memcpy (btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN);
1818                 p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
1819                 btm_cb.pairing_flags |= BTM_PAIR_FLAGS_LE_ACTIVE;
1820                 /* fall through */
1821
1822             case SMP_COMPLT_EVT:
1823                 if (btm_cb.api.p_le_callback)
1824                 {
1825                     /* the callback function implementation may change the IO capability... */
1826                     BTM_TRACE_DEBUG ("btm_cb.api.p_le_callback=0x%x", btm_cb.api.p_le_callback );
1827                    (*btm_cb.api.p_le_callback) (event, bd_addr, (tBTM_LE_EVT_DATA *)p_data);
1828                 }
1829
1830                 if (event == SMP_COMPLT_EVT)
1831                 {
1832                     BTM_TRACE_DEBUG ("evt=SMP_COMPLT_EVT before update sec_level=0x%x sec_flags=0x%x", p_data->cmplt.sec_level , p_dev_rec->sec_flags );
1833
1834                     res = (p_data->cmplt.reason == SMP_SUCCESS) ? BTM_SUCCESS : BTM_ERR_PROCESSING;
1835
1836                     BTM_TRACE_DEBUG ("after update result=%d sec_level=0x%x sec_flags=0x%x",
1837                                       res, p_data->cmplt.sec_level , p_dev_rec->sec_flags );
1838
1839                     if (p_data->cmplt.is_pair_cancel && btm_cb.api.p_bond_cancel_cmpl_callback )
1840                     {
1841                         BTM_TRACE_DEBUG ("Pairing Cancel completed");
1842                         (*btm_cb.api.p_bond_cancel_cmpl_callback)(BTM_SUCCESS);
1843                     }
1844 #if BTM_BLE_CONFORMANCE_TESTING == TRUE
1845                     if (res != BTM_SUCCESS)
1846                     {
1847                         if (!btm_cb.devcb.no_disc_if_pair_fail && p_data->cmplt.reason != SMP_CONN_TOUT)
1848                         {
1849                             BTM_TRACE_DEBUG ("Pairing failed - prepare to remove ACL");
1850                             l2cu_start_post_bond_timer(p_dev_rec->ble_hci_handle);
1851                         }
1852                         else
1853                         {
1854                             BTM_TRACE_DEBUG ("Pairing failed - Not Removing ACL");
1855                             p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
1856                         }
1857                     }
1858 #else
1859                     if (res != BTM_SUCCESS && p_data->cmplt.reason != SMP_CONN_TOUT)
1860                     {
1861                         BTM_TRACE_DEBUG ("Pairing failed - prepare to remove ACL");
1862                         l2cu_start_post_bond_timer(p_dev_rec->ble_hci_handle);
1863                     }
1864 #endif
1865
1866                     BTM_TRACE_DEBUG ("btm_cb pairing_state=%x pairing_flags=%x pin_code_len=%x",
1867                                       btm_cb.pairing_state,
1868                                       btm_cb.pairing_flags,
1869                                       btm_cb.pin_code_len  );
1870                     BTM_TRACE_DEBUG ("btm_cb.pairing_bda %02x:%02x:%02x:%02x:%02x:%02x",
1871                                       btm_cb.pairing_bda[0], btm_cb.pairing_bda[1], btm_cb.pairing_bda[2],
1872                                       btm_cb.pairing_bda[3], btm_cb.pairing_bda[4], btm_cb.pairing_bda[5]);
1873
1874                     /* Reset btm state only if the callback address matches pairing address*/
1875                     if(memcmp(bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) == 0)
1876                     {
1877                         memset (btm_cb.pairing_bda, 0xff, BD_ADDR_LEN);
1878                         btm_cb.pairing_state = BTM_PAIR_STATE_IDLE;
1879                         btm_cb.pairing_flags = 0;
1880                     }
1881
1882                     if (res == BTM_SUCCESS)
1883                     {
1884                         p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
1885 #if (defined BLE_PRIVACY_SPT && BLE_PRIVACY_SPT == TRUE)
1886                         /* add all bonded device into resolving list if IRK is available*/
1887                         btm_ble_resolving_list_load_dev(p_dev_rec);
1888 #endif
1889                     }
1890
1891                     btm_sec_dev_rec_cback_event(p_dev_rec, res, TRUE);
1892                 }
1893                 break;
1894
1895             default:
1896                 BTM_TRACE_DEBUG ("unknown event = %d", event);
1897                 break;
1898
1899
1900         }
1901     }
1902     else
1903     {
1904         BTM_TRACE_ERROR("btm_proc_smp_cback received for unknown device");
1905     }
1906
1907     return 0;
1908 }
1909
1910     #endif  /* SMP_INCLUDED */
1911
1912 /*******************************************************************************
1913 **
1914 ** Function         BTM_BleDataSignature
1915 **
1916 ** Description      This function is called to sign the data using AES128 CMAC
1917 **                  algorith.
1918 **
1919 ** Parameter        bd_addr: target device the data to be signed for.
1920 **                  p_text: singing data
1921 **                  len: length of the data to be signed.
1922 **                  signature: output parameter where data signature is going to
1923 **                             be stored.
1924 **
1925 ** Returns          TRUE if signing sucessul, otherwise FALSE.
1926 **
1927 *******************************************************************************/
1928 BOOLEAN BTM_BleDataSignature (BD_ADDR bd_addr, UINT8 *p_text, UINT16 len,
1929                               BLE_SIGNATURE signature)
1930 {
1931     tBTM_SEC_DEV_REC *p_rec = btm_find_dev (bd_addr);
1932
1933     BTM_TRACE_DEBUG ("%s", __func__);
1934     BOOLEAN ret = FALSE;
1935     if (p_rec == NULL)
1936     {
1937         BTM_TRACE_ERROR("%s-data signing can not be done from unknown device", __func__);
1938     }
1939     else
1940     {
1941         UINT8 *p_mac = (UINT8 *)signature;
1942         UINT8 *p_buf, *pp;
1943         if ((p_buf = (UINT8 *)GKI_getbuf((UINT16)(len + 4))) != NULL)
1944         {
1945             BTM_TRACE_DEBUG("%s-Start to generate Local CSRK", __func__);
1946             pp = p_buf;
1947             /* prepare plain text */
1948             if (p_text)
1949             {
1950                 memcpy(p_buf, p_text, len);
1951                 pp = (p_buf + len);
1952             }
1953
1954             UINT32_TO_STREAM(pp, p_rec->ble.keys.local_counter);
1955             UINT32_TO_STREAM(p_mac, p_rec->ble.keys.local_counter);
1956
1957             if ((ret = aes_cipher_msg_auth_code(p_rec->ble.keys.lcsrk, p_buf, (UINT16)(len + 4),
1958                                         BTM_CMAC_TLEN_SIZE, p_mac)) == TRUE)
1959             {
1960                   btm_ble_increment_sign_ctr(bd_addr, TRUE);
1961             }
1962
1963             BTM_TRACE_DEBUG("%s p_mac = %d", __func__, p_mac);
1964             BTM_TRACE_DEBUG("p_mac[0] = 0x%02x p_mac[1] = 0x%02x p_mac[2] = 0x%02x p_mac[3] = 0x%02x",
1965                              *p_mac, *(p_mac + 1), *(p_mac + 2), *(p_mac + 3));
1966             BTM_TRACE_DEBUG("p_mac[4] = 0x%02x p_mac[5] = 0x%02x p_mac[6] = 0x%02x p_mac[7] = 0x%02x",
1967                             *(p_mac + 4), *(p_mac + 5), *(p_mac + 6), *(p_mac + 7));
1968             GKI_freebuf(p_buf);
1969         }
1970     }
1971     return ret;
1972 }
1973
1974 /*******************************************************************************
1975 **
1976 ** Function         BTM_BleVerifySignature
1977 **
1978 ** Description      This function is called to verify the data signature
1979 **
1980 ** Parameter        bd_addr: target device the data to be signed for.
1981 **                  p_orig:  original data before signature.
1982 **                  len: length of the signing data
1983 **                  counter: counter used when doing data signing
1984 **                  p_comp: signature to be compared against.
1985
1986 ** Returns          TRUE if signature verified correctly; otherwise FALSE.
1987 **
1988 *******************************************************************************/
1989 BOOLEAN BTM_BleVerifySignature (BD_ADDR bd_addr, UINT8 *p_orig, UINT16 len, UINT32 counter,
1990                                 UINT8 *p_comp)
1991 {
1992     BOOLEAN verified = FALSE;
1993 #if SMP_INCLUDED == TRUE
1994     tBTM_SEC_DEV_REC *p_rec = btm_find_dev (bd_addr);
1995     UINT8 p_mac[BTM_CMAC_TLEN_SIZE];
1996
1997     if (p_rec == NULL || (p_rec && !(p_rec->ble.key_type & BTM_LE_KEY_PCSRK)))
1998     {
1999         BTM_TRACE_ERROR("can not verify signature for unknown device");
2000     }
2001     else if (counter < p_rec->ble.keys.counter)
2002     {
2003         BTM_TRACE_ERROR("signature received with out dated sign counter");
2004     }
2005     else if (p_orig == NULL)
2006     {
2007         BTM_TRACE_ERROR("No signature to verify");
2008     }
2009     else
2010     {
2011         BTM_TRACE_DEBUG ("%s rcv_cnt=%d >= expected_cnt=%d", __func__, counter,
2012                           p_rec->ble.keys.counter);
2013
2014         if (aes_cipher_msg_auth_code(p_rec->ble.keys.pcsrk, p_orig, len, BTM_CMAC_TLEN_SIZE, p_mac))
2015         {
2016             if (memcmp(p_mac, p_comp, BTM_CMAC_TLEN_SIZE) == 0)
2017             {
2018                 btm_ble_increment_sign_ctr(bd_addr, FALSE);
2019                 verified = TRUE;
2020             }
2021         }
2022     }
2023 #endif  /* SMP_INCLUDED */
2024     return verified;
2025 }
2026
2027 /*******************************************************************************
2028 **
2029 ** Function         BTM_GetLeSecurityState
2030 **
2031 ** Description      This function is called to get security mode 1 flags and
2032 **                  encryption key size for LE peer.
2033 **
2034 ** Returns          BOOLEAN TRUE if LE device is found, FALSE otherwise.
2035 **
2036 *******************************************************************************/
2037 BOOLEAN BTM_GetLeSecurityState (BD_ADDR bd_addr, UINT8 *p_le_dev_sec_flags, UINT8 *p_le_key_size)
2038 {
2039 #if (BLE_INCLUDED == TRUE)
2040     tBTM_SEC_DEV_REC *p_dev_rec;
2041     UINT16 dev_rec_sec_flags;
2042 #endif
2043
2044     *p_le_dev_sec_flags = 0;
2045     *p_le_key_size = 0;
2046
2047 #if (BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE)
2048     if ((p_dev_rec = btm_find_dev (bd_addr)) == NULL)
2049     {
2050         BTM_TRACE_ERROR ("%s fails", __func__);
2051         return (FALSE);
2052     }
2053
2054     if (p_dev_rec->ble_hci_handle == BTM_SEC_INVALID_HANDLE)
2055     {
2056         BTM_TRACE_ERROR ("%s-this is not LE device", __func__);
2057         return (FALSE);
2058     }
2059
2060     dev_rec_sec_flags = p_dev_rec->sec_flags;
2061
2062     if (dev_rec_sec_flags & BTM_SEC_LE_ENCRYPTED)
2063     {
2064         /* link is encrypted with LTK or STK */
2065         *p_le_key_size = p_dev_rec->enc_key_size;
2066         *p_le_dev_sec_flags |= BTM_SEC_LE_LINK_ENCRYPTED;
2067
2068         *p_le_dev_sec_flags |= (dev_rec_sec_flags & BTM_SEC_LE_AUTHENTICATED)
2069             ? BTM_SEC_LE_LINK_PAIRED_WITH_MITM      /* set auth LTK flag */
2070             : BTM_SEC_LE_LINK_PAIRED_WITHOUT_MITM;  /* set unauth LTK flag */
2071     }
2072     else if (p_dev_rec->ble.key_type & BTM_LE_KEY_PENC)
2073     {
2074         /* link is unencrypted, still LTK is available */
2075         *p_le_key_size = p_dev_rec->ble.keys.key_size;
2076
2077         *p_le_dev_sec_flags |= (dev_rec_sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED)
2078             ? BTM_SEC_LE_LINK_PAIRED_WITH_MITM      /* set auth LTK flag */
2079             : BTM_SEC_LE_LINK_PAIRED_WITHOUT_MITM;  /* set unauth LTK flag */
2080     }
2081
2082     BTM_TRACE_DEBUG ("%s - le_dev_sec_flags: 0x%02x, le_key_size: %d",
2083         __func__, *p_le_dev_sec_flags, *p_le_key_size);
2084
2085     return TRUE;
2086 #else
2087     return FALSE;
2088 #endif
2089 }
2090
2091 /*******************************************************************************
2092 **
2093 ** Function         BTM_BleSecurityProcedureIsRunning
2094 **
2095 ** Description      This function indicates if LE security procedure is
2096 **                  currently running with the peer.
2097 **
2098 ** Returns          BOOLEAN TRUE if security procedure is running, FALSE otherwise.
2099 **
2100 *******************************************************************************/
2101 BOOLEAN BTM_BleSecurityProcedureIsRunning(BD_ADDR bd_addr)
2102 {
2103 #if (BLE_INCLUDED == TRUE)
2104     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bd_addr);
2105
2106     if (p_dev_rec == NULL)
2107     {
2108         BTM_TRACE_ERROR ("%s device with BDA: %08x%04x is not found",
2109                           __func__, (bd_addr[0]<<24)+(bd_addr[1]<<16)+(bd_addr[2]<<8)+bd_addr[3],
2110                           (bd_addr[4]<<8)+bd_addr[5]);
2111         return FALSE;
2112     }
2113
2114     return (p_dev_rec->sec_state == BTM_SEC_STATE_ENCRYPTING ||
2115             p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING);
2116 #else
2117     return FALSE;
2118 #endif
2119 }
2120
2121 /*******************************************************************************
2122 **
2123 ** Function         BTM_BleGetSupportedKeySize
2124 **
2125 ** Description      This function gets the maximum encryption key size in bytes
2126 **                  the local device can suport.
2127 **                  record.
2128 **
2129 ** Returns          the key size or 0 if the size can't be retrieved.
2130 **
2131 *******************************************************************************/
2132 extern UINT8 BTM_BleGetSupportedKeySize (BD_ADDR bd_addr)
2133 {
2134 #if ((BLE_INCLUDED == TRUE) && (L2CAP_LE_COC_INCLUDED == TRUE))
2135     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bd_addr);
2136     tBTM_LE_IO_REQ dev_io_cfg;
2137     UINT8 callback_rc;
2138
2139     if (!p_dev_rec)
2140     {
2141         BTM_TRACE_ERROR ("%s device with BDA: %08x%04x is not found",
2142                          __func__,(bd_addr[0]<<24)+(bd_addr[1]<<16)+(bd_addr[2]<<8)+bd_addr[3],
2143                           (bd_addr[4]<<8)+bd_addr[5]);
2144         return 0;
2145     }
2146
2147     if (btm_cb.api.p_le_callback == NULL)
2148     {
2149         BTM_TRACE_ERROR ("%s can't access supported key size",__func__);
2150         return 0;
2151     }
2152
2153     callback_rc = (*btm_cb.api.p_le_callback) (BTM_LE_IO_REQ_EVT, p_dev_rec->bd_addr,
2154                                                (tBTM_LE_EVT_DATA *) &dev_io_cfg);
2155
2156     if (callback_rc != BTM_SUCCESS)
2157     {
2158         BTM_TRACE_ERROR ("%s can't access supported key size",__func__);
2159         return 0;
2160     }
2161
2162     BTM_TRACE_DEBUG ("%s device supports key size = %d", __func__, dev_io_cfg.max_key_size);
2163     return (dev_io_cfg.max_key_size);
2164 #else
2165     return 0;
2166 #endif
2167 }
2168
2169 /*******************************************************************************
2170 **  Utility functions for LE device IR/ER generation
2171 *******************************************************************************/
2172 /*******************************************************************************
2173 **
2174 ** Function         btm_notify_new_key
2175 **
2176 ** Description      This function is to notify application new keys have been
2177 **                  generated.
2178 **
2179 ** Returns          void
2180 **
2181 *******************************************************************************/
2182 static void btm_notify_new_key(UINT8 key_type)
2183 {
2184     tBTM_BLE_LOCAL_KEYS *p_locak_keys = NULL;
2185
2186     BTM_TRACE_DEBUG ("btm_notify_new_key key_type=%d", key_type);
2187
2188     if (btm_cb.api.p_le_key_callback)
2189     {
2190         switch (key_type)
2191         {
2192             case BTM_BLE_KEY_TYPE_ID:
2193                 BTM_TRACE_DEBUG ("BTM_BLE_KEY_TYPE_ID");
2194                 p_locak_keys = (tBTM_BLE_LOCAL_KEYS *)&btm_cb.devcb.id_keys;
2195                 break;
2196
2197             case BTM_BLE_KEY_TYPE_ER:
2198                 BTM_TRACE_DEBUG ("BTM_BLE_KEY_TYPE_ER");
2199                 p_locak_keys = (tBTM_BLE_LOCAL_KEYS *)&btm_cb.devcb.ble_encryption_key_value;
2200                 break;
2201
2202             default:
2203                 BTM_TRACE_ERROR("unknown key type: %d", key_type);
2204                 break;
2205         }
2206         if (p_locak_keys != NULL)
2207             (*btm_cb.api.p_le_key_callback) (key_type, p_locak_keys);
2208     }
2209 }
2210
2211 /*******************************************************************************
2212 **
2213 ** Function         btm_ble_process_er2
2214 **
2215 ** Description      This function is called when ER is generated, store it in
2216 **                  local control block.
2217 **
2218 ** Returns          void
2219 **
2220 *******************************************************************************/
2221 static void btm_ble_process_er2(tBTM_RAND_ENC *p)
2222 {
2223     BTM_TRACE_DEBUG ("btm_ble_process_er2");
2224
2225     if (p &&p->opcode == HCI_BLE_RAND)
2226     {
2227         memcpy(&btm_cb.devcb.ble_encryption_key_value[8], p->param_buf, BT_OCTET8_LEN);
2228         btm_notify_new_key(BTM_BLE_KEY_TYPE_ER);
2229     }
2230     else
2231     {
2232         BTM_TRACE_ERROR("Generating ER2 exception.");
2233         memset(&btm_cb.devcb.ble_encryption_key_value, 0, sizeof(BT_OCTET16));
2234     }
2235 }
2236
2237 /*******************************************************************************
2238 **
2239 ** Function         btm_ble_process_er
2240 **
2241 ** Description      This function is called when ER is generated, store it in
2242 **                  local control block.
2243 **
2244 ** Returns          void
2245 **
2246 *******************************************************************************/
2247 static void btm_ble_process_er(tBTM_RAND_ENC *p)
2248 {
2249     BTM_TRACE_DEBUG ("btm_ble_process_er");
2250
2251     if (p &&p->opcode == HCI_BLE_RAND)
2252     {
2253         memcpy(&btm_cb.devcb.ble_encryption_key_value[0], p->param_buf, BT_OCTET8_LEN);
2254
2255         if (!btsnd_hcic_ble_rand((void *)btm_ble_process_er2))
2256         {
2257             memset(&btm_cb.devcb.ble_encryption_key_value, 0, sizeof(BT_OCTET16));
2258             BTM_TRACE_ERROR("Generating ER2 failed.");
2259         }
2260     }
2261     else
2262     {
2263         BTM_TRACE_ERROR("Generating ER1 exception.");
2264     }
2265 }
2266
2267 /*******************************************************************************
2268 **
2269 ** Function         btm_ble_process_irk
2270 **
2271 ** Description      This function is called when IRK is generated, store it in
2272 **                  local control block.
2273 **
2274 ** Returns          void
2275 **
2276 *******************************************************************************/
2277 static void btm_ble_process_irk(tSMP_ENC *p)
2278 {
2279     BTM_TRACE_DEBUG ("btm_ble_process_irk");
2280     if (p &&p->opcode == HCI_BLE_ENCRYPT)
2281     {
2282         memcpy(btm_cb.devcb.id_keys.irk, p->param_buf, BT_OCTET16_LEN);
2283         btm_notify_new_key(BTM_BLE_KEY_TYPE_ID);
2284     }
2285     else
2286     {
2287         BTM_TRACE_ERROR("Generating IRK exception.");
2288     }
2289
2290     /* proceed generate ER */
2291     if (!btsnd_hcic_ble_rand((void *)btm_ble_process_er))
2292     {
2293         BTM_TRACE_ERROR("Generating ER failed.");
2294     }
2295 }
2296
2297 /*******************************************************************************
2298 **
2299 ** Function         btm_ble_process_dhk
2300 **
2301 ** Description      This function is called when DHK is calculated, store it in
2302 **                  local control block, and proceed to generate ER, a 128-bits
2303 **                  random number.
2304 **
2305 ** Returns          void
2306 **
2307 *******************************************************************************/
2308 static void btm_ble_process_dhk(tSMP_ENC *p)
2309 {
2310 #if SMP_INCLUDED == TRUE
2311     UINT8 btm_ble_irk_pt = 0x01;
2312     tSMP_ENC output;
2313
2314     BTM_TRACE_DEBUG ("btm_ble_process_dhk");
2315
2316     if (p && p->opcode == HCI_BLE_ENCRYPT)
2317     {
2318         memcpy(btm_cb.devcb.id_keys.dhk, p->param_buf, BT_OCTET16_LEN);
2319         BTM_TRACE_DEBUG("BLE DHK generated.");
2320
2321         /* IRK = D1(IR, 1) */
2322         if (!SMP_Encrypt(btm_cb.devcb.id_keys.ir, BT_OCTET16_LEN, &btm_ble_irk_pt,
2323                          1,   &output))
2324         {
2325             /* reset all identity root related key */
2326             memset(&btm_cb.devcb.id_keys, 0, sizeof(tBTM_BLE_LOCAL_ID_KEYS));
2327         }
2328         else
2329         {
2330             btm_ble_process_irk(&output);
2331         }
2332     }
2333     else
2334     {
2335         /* reset all identity root related key */
2336         memset(&btm_cb.devcb.id_keys, 0, sizeof(tBTM_BLE_LOCAL_ID_KEYS));
2337     }
2338 #endif
2339 }
2340
2341 /*******************************************************************************
2342 **
2343 ** Function         btm_ble_process_ir2
2344 **
2345 ** Description      This function is called when IR is generated, proceed to calculate
2346 **                  DHK = Eir({0x03, 0, 0 ...})
2347 **
2348 **
2349 ** Returns          void
2350 **
2351 *******************************************************************************/
2352 static void btm_ble_process_ir2(tBTM_RAND_ENC *p)
2353 {
2354 #if SMP_INCLUDED == TRUE
2355     UINT8 btm_ble_dhk_pt = 0x03;
2356     tSMP_ENC output;
2357
2358     BTM_TRACE_DEBUG ("btm_ble_process_ir2");
2359
2360     if (p && p->opcode == HCI_BLE_RAND)
2361     {
2362         /* remembering in control block */
2363         memcpy(&btm_cb.devcb.id_keys.ir[8], p->param_buf, BT_OCTET8_LEN);
2364         /* generate DHK= Eir({0x03, 0x00, 0x00 ...}) */
2365
2366
2367         SMP_Encrypt(btm_cb.devcb.id_keys.ir, BT_OCTET16_LEN, &btm_ble_dhk_pt,
2368                     1, &output);
2369         btm_ble_process_dhk(&output);
2370
2371         BTM_TRACE_DEBUG("BLE IR generated.");
2372     }
2373     else
2374     {
2375         memset(&btm_cb.devcb.id_keys, 0, sizeof(tBTM_BLE_LOCAL_ID_KEYS));
2376     }
2377 #endif
2378 }
2379
2380 /*******************************************************************************
2381 **
2382 ** Function         btm_ble_process_ir
2383 **
2384 ** Description      This function is called when IR is generated, proceed to calculate
2385 **                  DHK = Eir({0x02, 0, 0 ...})
2386 **
2387 **
2388 ** Returns          void
2389 **
2390 *******************************************************************************/
2391 static void btm_ble_process_ir(tBTM_RAND_ENC *p)
2392 {
2393     BTM_TRACE_DEBUG ("btm_ble_process_ir");
2394
2395     if (p && p->opcode == HCI_BLE_RAND)
2396     {
2397         /* remembering in control block */
2398         memcpy(btm_cb.devcb.id_keys.ir, p->param_buf, BT_OCTET8_LEN);
2399
2400         if (!btsnd_hcic_ble_rand((void *)btm_ble_process_ir2))
2401         {
2402             BTM_TRACE_ERROR("Generating IR2 failed.");
2403             memset(&btm_cb.devcb.id_keys, 0, sizeof(tBTM_BLE_LOCAL_ID_KEYS));
2404         }
2405     }
2406 }
2407
2408 /*******************************************************************************
2409 **
2410 ** Function         btm_ble_reset_id
2411 **
2412 ** Description      This function is called to reset LE device identity.
2413 **
2414 ** Returns          void
2415 **
2416 *******************************************************************************/
2417 void btm_ble_reset_id( void )
2418 {
2419     BTM_TRACE_DEBUG ("btm_ble_reset_id");
2420
2421     /* regenrate Identity Root*/
2422     if (!btsnd_hcic_ble_rand((void *)btm_ble_process_ir))
2423     {
2424         BTM_TRACE_DEBUG("Generating IR failed.");
2425     }
2426 }
2427
2428     #if BTM_BLE_CONFORMANCE_TESTING == TRUE
2429 /*******************************************************************************
2430 **
2431 ** Function         btm_ble_set_no_disc_if_pair_fail
2432 **
2433 ** Description      This function indicates that whether no disconnect of the ACL
2434 **                  should be used if pairing failed
2435 **
2436 ** Returns          void
2437 **
2438 *******************************************************************************/
2439 void btm_ble_set_no_disc_if_pair_fail(BOOLEAN disable_disc )
2440 {
2441     BTM_TRACE_DEBUG ("btm_ble_set_disc_enable_if_pair_fail disable_disc=%d", disable_disc);
2442     btm_cb.devcb.no_disc_if_pair_fail = disable_disc;
2443 }
2444
2445 /*******************************************************************************
2446 **
2447 ** Function         btm_ble_set_test_mac_value
2448 **
2449 ** Description      This function set test MAC value
2450 **
2451 ** Returns          void
2452 **
2453 *******************************************************************************/
2454 void btm_ble_set_test_mac_value(BOOLEAN enable, UINT8 *p_test_mac_val )
2455 {
2456     BTM_TRACE_DEBUG ("btm_ble_set_test_mac_value enable=%d", enable);
2457     btm_cb.devcb.enable_test_mac_val = enable;
2458     memcpy(btm_cb.devcb.test_mac, p_test_mac_val, BT_OCTET8_LEN);
2459 }
2460
2461 /*******************************************************************************
2462 **
2463 ** Function         btm_ble_set_test_local_sign_cntr_value
2464 **
2465 ** Description      This function set test local sign counter value
2466 **
2467 ** Returns          void
2468 **
2469 *******************************************************************************/
2470 void btm_ble_set_test_local_sign_cntr_value(BOOLEAN enable, UINT32 test_local_sign_cntr )
2471 {
2472     BTM_TRACE_DEBUG ("btm_ble_set_test_local_sign_cntr_value enable=%d local_sign_cntr=%d",
2473                       enable, test_local_sign_cntr);
2474     btm_cb.devcb.enable_test_local_sign_cntr = enable;
2475     btm_cb.devcb.test_local_sign_cntr =  test_local_sign_cntr;
2476 }
2477
2478 /*******************************************************************************
2479 **
2480 ** Function         btm_set_random_address
2481 **
2482 ** Description      This function set a random address to local controller.
2483 **
2484 ** Returns          void
2485 **
2486 *******************************************************************************/
2487 void btm_set_random_address(BD_ADDR random_bda)
2488 {
2489     tBTM_LE_RANDOM_CB *p_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
2490     BOOLEAN     adv_mode = btm_cb.ble_ctr_cb.inq_var.adv_mode ;
2491
2492     BTM_TRACE_DEBUG ("btm_set_random_address");
2493
2494     if (adv_mode  == BTM_BLE_ADV_ENABLE)
2495         btsnd_hcic_ble_set_adv_enable (BTM_BLE_ADV_DISABLE);
2496
2497     memcpy(p_cb->private_addr, random_bda, BD_ADDR_LEN);
2498     btsnd_hcic_ble_set_random_addr(p_cb->private_addr);
2499
2500     if (adv_mode  == BTM_BLE_ADV_ENABLE)
2501         btsnd_hcic_ble_set_adv_enable (BTM_BLE_ADV_ENABLE);
2502
2503
2504 }
2505
2506 /*******************************************************************************
2507 **
2508 ** Function         btm_ble_set_keep_rfu_in_auth_req
2509 **
2510 ** Description      This function indicates if RFU bits have to be kept as is
2511 **                  (by default they have to be set to 0 by the sender).
2512 **
2513 ** Returns          void
2514 **
2515 *******************************************************************************/
2516 void btm_ble_set_keep_rfu_in_auth_req(BOOLEAN keep_rfu)
2517 {
2518     BTM_TRACE_DEBUG ("btm_ble_set_keep_rfu_in_auth_req keep_rfus=%d", keep_rfu);
2519     btm_cb.devcb.keep_rfu_in_auth_req = keep_rfu;
2520 }
2521
2522 #endif /* BTM_BLE_CONFORMANCE_TESTING */
2523
2524 #endif /* BLE_INCLUDED */