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