OSDN Git Service

Merge commit 'd9bb94c' into merge2
[android-x86/system-bt.git] / stack / btm / btm_sec.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 the Bluetooth Security Manager
22  *
23  ******************************************************************************/
24
25 #define LOG_TAG "bt_btm_sec"
26
27 #include <stdarg.h>
28 #include <string.h>
29
30 #include "bt_types.h"
31 #include "device/include/controller.h"
32 #include "hcimsgs.h"
33 #include "btu.h"
34 #include "btm_int.h"
35 #include "l2c_int.h"
36 #include "bt_utils.h"
37 #include "osi/include/log.h"
38
39 #if (BT_USE_TRACES == TRUE && BT_TRACE_VERBOSE == FALSE)
40 /* needed for sprintf() */
41 #include <stdio.h>
42 #endif
43
44 #if BLE_INCLUDED == TRUE
45     #include "gatt_int.h"
46 #endif
47
48 #define BTM_SEC_MAX_COLLISION_DELAY     (5000)
49
50 #ifdef APPL_AUTH_WRITE_EXCEPTION
51 BOOLEAN (APPL_AUTH_WRITE_EXCEPTION)(BD_ADDR bd_addr);
52 #endif
53
54
55 /********************************************************************************
56 **              L O C A L    F U N C T I O N     P R O T O T Y P E S            *
57 *********************************************************************************/
58 static tBTM_SEC_SERV_REC *btm_sec_find_first_serv (BOOLEAN is_originator, UINT16 psm);
59 static tBTM_SEC_SERV_REC *btm_sec_find_next_serv (tBTM_SEC_SERV_REC *p_cur);
60 static tBTM_SEC_SERV_REC *btm_sec_find_mx_serv (UINT8 is_originator, UINT16 psm,
61                                                 UINT32 mx_proto_id,
62                                                 UINT32 mx_chan_id);
63
64 static tBTM_STATUS btm_sec_execute_procedure (tBTM_SEC_DEV_REC *p_dev_rec);
65 static BOOLEAN  btm_sec_start_get_name (tBTM_SEC_DEV_REC *p_dev_rec);
66 static BOOLEAN  btm_sec_start_authentication (tBTM_SEC_DEV_REC *p_dev_rec);
67 static BOOLEAN  btm_sec_start_encryption (tBTM_SEC_DEV_REC *p_dev_rec);
68 static void     btm_sec_collision_timeout (TIMER_LIST_ENT *p_tle);
69 static void     btm_restore_mode(void);
70 static void     btm_sec_pairing_timeout (TIMER_LIST_ENT *p_tle);
71 static tBTM_STATUS btm_sec_dd_create_conn (tBTM_SEC_DEV_REC *p_dev_rec);
72 static void     btm_sec_change_pairing_state (tBTM_PAIRING_STATE new_state);
73
74 #if (BT_USE_TRACES == TRUE)
75 static char     *btm_pair_state_descr (tBTM_PAIRING_STATE state);
76 #endif
77
78 static void     btm_sec_check_pending_reqs(void);
79 static BOOLEAN  btm_sec_queue_mx_request (BD_ADDR bd_addr,  UINT16 psm,  BOOLEAN is_orig,
80                                           UINT32 mx_proto_id, UINT32 mx_chan_id,
81                                           tBTM_SEC_CALLBACK *p_callback, void *p_ref_data);
82 static void     btm_sec_bond_cancel_complete (void);
83 static void     btm_send_link_key_notif (tBTM_SEC_DEV_REC *p_dev_rec);
84 static BOOLEAN  btm_sec_check_prefetch_pin (tBTM_SEC_DEV_REC  *p_dev_rec);
85
86 static UINT8    btm_sec_start_authorization (tBTM_SEC_DEV_REC *p_dev_rec);
87 BOOLEAN         btm_sec_are_all_trusted(UINT32 p_mask[]);
88
89 static tBTM_STATUS btm_sec_send_hci_disconnect (tBTM_SEC_DEV_REC *p_dev_rec, UINT8 reason, UINT16 conn_handle);
90 UINT8           btm_sec_start_role_switch (tBTM_SEC_DEV_REC *p_dev_rec);
91 tBTM_SEC_DEV_REC *btm_sec_find_dev_by_sec_state (UINT8 state);
92
93 static BOOLEAN  btm_sec_set_security_level ( CONNECTION_TYPE conn_type, char *p_name, UINT8 service_id,
94                                             UINT16 sec_level, UINT16 psm, UINT32 mx_proto_id,
95                                             UINT32 mx_chan_id);
96
97 static BOOLEAN btm_dev_authenticated(tBTM_SEC_DEV_REC *p_dev_rec);
98 static BOOLEAN btm_dev_encrypted(tBTM_SEC_DEV_REC *p_dev_rec);
99 static BOOLEAN btm_dev_authorized(tBTM_SEC_DEV_REC *p_dev_rec);
100 static BOOLEAN btm_serv_trusted(tBTM_SEC_DEV_REC *p_dev_rec, tBTM_SEC_SERV_REC *p_serv_rec);
101 static BOOLEAN btm_sec_is_serv_level0 (UINT16 psm);
102 static UINT16  btm_sec_set_serv_level4_flags (UINT16 cur_security, BOOLEAN is_originator);
103
104 static BOOLEAN btm_sec_queue_encrypt_request  (BD_ADDR bd_addr, tBT_TRANSPORT transport,
105                                          tBTM_SEC_CALLBACK *p_callback, void *p_ref_data);
106 static void btm_sec_clean_pending_req_queue (BD_ADDR remote_bda, tBT_TRANSPORT transport) ;
107 static void btm_sec_check_pending_enc_req (tBTM_SEC_DEV_REC  *p_dev_rec, tBT_TRANSPORT transport,
108                                             UINT8 encr_enable);
109 static BOOLEAN btm_sec_acceptor_rejects_bonding (tBTM_SEC_DEV_REC *p_dev_rec);
110
111 static BOOLEAN btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC *p_dev_rec);
112 static BOOLEAN btm_sec_is_master(tBTM_SEC_DEV_REC *p_dev_rec);
113
114 /* TRUE - authenticated link key is possible */
115 static const BOOLEAN btm_sec_io_map [BTM_IO_CAP_MAX][BTM_IO_CAP_MAX] =
116 {
117     /*   OUT,    IO,     IN,     NONE */
118 /* OUT  */ {FALSE,  FALSE,  TRUE,   FALSE},
119 /* IO   */ {FALSE,  TRUE,   TRUE,   FALSE},
120 /* IN   */ {TRUE,   TRUE,   TRUE,   FALSE},
121 /* NONE */ {FALSE,  FALSE,  FALSE,  FALSE}
122 };
123 /*  BTM_IO_CAP_OUT      0   DisplayOnly */
124 /*  BTM_IO_CAP_IO       1   DisplayYesNo */
125 /*  BTM_IO_CAP_IN       2   KeyboardOnly */
126 /*  BTM_IO_CAP_NONE     3   NoInputNoOutput */
127
128 /*******************************************************************************
129 **
130 ** Function         btm_dev_authenticated
131 **
132 ** Description      check device is authenticated
133 **
134 ** Returns          BOOLEAN TRUE or FALSE
135 **
136 *******************************************************************************/
137 static BOOLEAN btm_dev_authenticated (tBTM_SEC_DEV_REC *p_dev_rec)
138 {
139     if(p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)
140     {
141         return(TRUE);
142     }
143     return(FALSE);
144 }
145
146 /*******************************************************************************
147 **
148 ** Function         btm_dev_encrypted
149 **
150 ** Description      check device is encrypted
151 **
152 ** Returns          BOOLEAN TRUE or FALSE
153 **
154 *******************************************************************************/
155 static BOOLEAN btm_dev_encrypted (tBTM_SEC_DEV_REC *p_dev_rec)
156 {
157     if(p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED)
158     {
159         return(TRUE);
160     }
161     return(FALSE);
162 }
163
164 /*******************************************************************************
165 **
166 ** Function         btm_dev_authorized
167 **
168 ** Description      check device is authorized
169 **
170 ** Returns          BOOLEAN TRUE or FALSE
171 **
172 *******************************************************************************/
173 static BOOLEAN btm_dev_authorized (tBTM_SEC_DEV_REC *p_dev_rec)
174 {
175     if(p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED)
176     {
177         return(TRUE);
178     }
179     return(FALSE);
180 }
181
182 /*******************************************************************************
183 **
184 ** Function         btm_serv_trusted
185 **
186 ** Description      check service is trusted
187 **
188 ** Returns          BOOLEAN TRUE or FALSE
189 **
190 *******************************************************************************/
191 static BOOLEAN btm_serv_trusted(tBTM_SEC_DEV_REC *p_dev_rec, tBTM_SEC_SERV_REC *p_serv_rec)
192 {
193     if(BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask, p_serv_rec->service_id))
194     {
195         return(TRUE);
196     }
197     return(FALSE);
198 }
199
200 /*******************************************************************************
201 **
202 ** Function         BTM_SecRegister
203 **
204 ** Description      Application manager calls this function to register for
205 **                  security services.  There can be one and only one application
206 **                  saving link keys.  BTM allows only first registration.
207 **
208 ** Returns          TRUE if registered OK, else FALSE
209 **
210 *******************************************************************************/
211 BOOLEAN BTM_SecRegister(tBTM_APPL_INFO *p_cb_info)
212 {
213 #if BLE_INCLUDED == TRUE
214     BT_OCTET16      temp_value = {0};
215 #endif
216
217     BTM_TRACE_EVENT("%s application registered", __func__);
218
219 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
220     LOG_INFO("%s p_cb_info->p_le_callback == 0x%p", __func__, p_cb_info->p_le_callback);
221     if (p_cb_info->p_le_callback)
222     {
223 #if SMP_INCLUDED == TRUE
224       BTM_TRACE_EVENT("%s SMP_Register( btm_proc_smp_cback )", __func__);
225       SMP_Register(btm_proc_smp_cback);
226 #endif
227       /* if no IR is loaded, need to regenerate all the keys */
228       if (memcmp(btm_cb.devcb.id_keys.ir, &temp_value, sizeof(BT_OCTET16)) == 0)
229       {
230         btm_ble_reset_id();
231       }
232     }
233     else
234     {
235       LOG_WARN("%s p_cb_info->p_le_callback == NULL", __func__);
236     }
237 #endif
238
239     btm_cb.api = *p_cb_info;
240 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
241      LOG_INFO("%s btm_cb.api.p_le_callback = 0x%p ", __func__, btm_cb.api.p_le_callback);
242 #endif
243     BTM_TRACE_EVENT("%s application registered", __func__);
244     return(TRUE);
245 }
246
247 /*******************************************************************************
248 **
249 ** Function         BTM_SecAddRmtNameNotifyCallback
250 **
251 ** Description      Any profile can register to be notified when name of the
252 **                  remote device is resolved.
253 **
254 ** Returns          TRUE if registered OK, else FALSE
255 **
256 *******************************************************************************/
257 BOOLEAN  BTM_SecAddRmtNameNotifyCallback (tBTM_RMT_NAME_CALLBACK *p_callback)
258 {
259     int i;
260
261     for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++)
262     {
263         if (btm_cb.p_rmt_name_callback[i] == NULL)
264         {
265             btm_cb.p_rmt_name_callback[i] = p_callback;
266             return(TRUE);
267         }
268     }
269
270     return(FALSE);
271 }
272
273
274 /*******************************************************************************
275 **
276 ** Function         BTM_SecDeleteRmtNameNotifyCallback
277 **
278 ** Description      Any profile can deregister notification when a new Link Key
279 **                  is generated per connection.
280 **
281 ** Returns          TRUE if OK, else FALSE
282 **
283 *******************************************************************************/
284 BOOLEAN  BTM_SecDeleteRmtNameNotifyCallback (tBTM_RMT_NAME_CALLBACK *p_callback)
285 {
286     int i;
287
288     for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++)
289     {
290         if (btm_cb.p_rmt_name_callback[i] == p_callback)
291         {
292             btm_cb.p_rmt_name_callback[i] = NULL;
293             return(TRUE);
294         }
295     }
296
297     return(FALSE);
298 }
299
300 /*******************************************************************************
301 **
302 ** Function         BTM_GetSecurityFlags
303 **
304 ** Description      Get security flags for the device
305 **
306 ** Returns          BOOLEAN TRUE or FALSE is device found
307 **
308 *******************************************************************************/
309 BOOLEAN BTM_GetSecurityFlags (BD_ADDR bd_addr, UINT8 * p_sec_flags)
310 {
311     tBTM_SEC_DEV_REC *p_dev_rec;
312
313     if ((p_dev_rec = btm_find_dev (bd_addr)) != NULL)
314     {
315         *p_sec_flags = (UINT8) p_dev_rec->sec_flags;
316         return(TRUE);
317     }
318     BTM_TRACE_ERROR ("BTM_GetSecurityFlags false");
319     return(FALSE);
320 }
321
322 /*******************************************************************************
323 **
324 ** Function         BTM_GetSecurityFlagsByTransport
325 **
326 ** Description      Get security flags for the device on a particular transport
327 **
328 ** Returns          BOOLEAN TRUE or FALSE is device found
329 **
330 *******************************************************************************/
331 BOOLEAN BTM_GetSecurityFlagsByTransport (BD_ADDR bd_addr, UINT8 * p_sec_flags,
332                                                 tBT_TRANSPORT transport)
333 {
334     tBTM_SEC_DEV_REC *p_dev_rec;
335
336     if ((p_dev_rec = btm_find_dev (bd_addr)) != NULL)
337     {
338         if (transport == BT_TRANSPORT_BR_EDR)
339             *p_sec_flags = (UINT8) p_dev_rec->sec_flags;
340         else
341             *p_sec_flags = (UINT8) (p_dev_rec->sec_flags >> 8);
342
343         return(TRUE);
344     }
345     BTM_TRACE_ERROR ("BTM_GetSecurityFlags false");
346     return(FALSE);
347 }
348
349 /*******************************************************************************
350 **
351 ** Function         BTM_SetPinType
352 **
353 ** Description      Set PIN type for the device.
354 **
355 ** Returns          void
356 **
357 *******************************************************************************/
358 void BTM_SetPinType (UINT8 pin_type, PIN_CODE pin_code, UINT8 pin_code_len)
359 {
360     BTM_TRACE_API ("BTM_SetPinType: pin type %d [variable-0, fixed-1], code %s, length %d",
361                     pin_type, (char *) pin_code, pin_code_len);
362
363     /* If device is not up security mode will be set as a part of startup */
364     if ( (btm_cb.cfg.pin_type != pin_type)
365          && controller_get_interface()->get_is_ready() )
366     {
367         btsnd_hcic_write_pin_type (pin_type);
368     }
369
370     btm_cb.cfg.pin_type     = pin_type;
371     btm_cb.cfg.pin_code_len = pin_code_len;
372     memcpy (btm_cb.cfg.pin_code, pin_code, pin_code_len);
373 }
374
375 /*******************************************************************************
376 **
377 ** Function         BTM_SetPairableMode
378 **
379 ** Description      Enable or disable pairing
380 **
381 ** Parameters       allow_pairing - (TRUE or FALSE) whether or not the device
382 **                      allows pairing.
383 **                  connect_only_paired - (TRUE or FALSE) whether or not to
384 **                      only allow paired devices to connect.
385 **
386 ** Returns          void
387 **
388 *******************************************************************************/
389 void BTM_SetPairableMode (BOOLEAN allow_pairing, BOOLEAN connect_only_paired)
390 {
391     BTM_TRACE_API ("BTM_SetPairableMode()  allow_pairing: %u   connect_only_paired: %u", allow_pairing, connect_only_paired);
392
393     btm_cb.pairing_disabled    = !allow_pairing;
394     btm_cb.connect_only_paired = connect_only_paired;
395 }
396
397 /*******************************************************************************
398 **
399 ** Function         BTM_SetSecureConnectionsOnly
400 **
401 ** Description      Enable or disable default treatment for Mode 4 Level 0 services
402 **
403 ** Parameter        secure_connections_only_mode - (TRUE or FALSE) whether or not the device
404 **                  TRUE means that the device should treat Mode 4 Level 0 services as
405 **                  services of other levels. (Secure_connections_only_mode)
406 **                  FALSE means that the device should provide default treatment for
407 **                  Mode 4 Level 0 services.
408 **
409 ** Returns          void
410 **
411 *******************************************************************************/
412 void BTM_SetSecureConnectionsOnly (BOOLEAN secure_connections_only_mode)
413 {
414     BTM_TRACE_API("%s: Mode : %u", __FUNCTION__,
415                    secure_connections_only_mode);
416
417     btm_cb.devcb.secure_connections_only = secure_connections_only_mode;
418 }
419 #define BTM_NO_AVAIL_SEC_SERVICES   ((UINT16) 0xffff)
420
421 /*******************************************************************************
422 **
423 ** Function         BTM_SetSecurityLevel
424 **
425 ** Description      Register service security level with Security Manager
426 **
427 ** Parameters:      is_originator - TRUE if originating the connection, FALSE if not
428 **                  p_name      - Name of the service relevant only if
429 **                                authorization will show this name to user. ignored
430 **                                if BTM_SEC_SERVICE_NAME_LEN is 0.
431 **                  service_id  - service ID for the service passed to authorization callback
432 **                  sec_level   - bit mask of the security features
433 **                  psm         - L2CAP PSM
434 **                  mx_proto_id - protocol ID of multiplexing proto below
435 **                  mx_chan_id  - channel ID of multiplexing proto below
436 **
437 ** Returns          TRUE if registered OK, else FALSE
438 **
439 *******************************************************************************/
440 BOOLEAN BTM_SetSecurityLevel (BOOLEAN is_originator, char *p_name, UINT8 service_id,
441                               UINT16 sec_level, UINT16 psm, UINT32 mx_proto_id,
442                               UINT32 mx_chan_id)
443 {
444 #if (L2CAP_UCD_INCLUDED == TRUE)
445     CONNECTION_TYPE conn_type;
446
447     if (is_originator)
448         conn_type = CONN_ORIENT_ORIG;
449     else
450         conn_type = CONN_ORIENT_TERM;
451
452     return(btm_sec_set_security_level (conn_type, p_name, service_id,
453                                        sec_level, psm, mx_proto_id, mx_chan_id));
454 #else
455     return(btm_sec_set_security_level (is_originator, p_name, service_id,
456                                        sec_level, psm, mx_proto_id, mx_chan_id));
457 #endif
458 }
459
460 /*******************************************************************************
461 **
462 ** Function         btm_sec_set_security_level
463 **
464 ** Description      Register service security level with Security Manager
465 **
466 ** Parameters:      conn_type   - TRUE if originating the connection, FALSE if not
467 **                  p_name      - Name of the service relevant only if
468 **                                authorization will show this name to user. ignored
469 **                                if BTM_SEC_SERVICE_NAME_LEN is 0.
470 **                  service_id  - service ID for the service passed to authorization callback
471 **                  sec_level   - bit mask of the security features
472 **                  psm         - L2CAP PSM
473 **                  mx_proto_id - protocol ID of multiplexing proto below
474 **                  mx_chan_id  - channel ID of multiplexing proto below
475 **
476 ** Returns          TRUE if registered OK, else FALSE
477 **
478 *******************************************************************************/
479 static BOOLEAN btm_sec_set_security_level (CONNECTION_TYPE conn_type, char *p_name, UINT8 service_id,
480                                            UINT16 sec_level, UINT16 psm, UINT32 mx_proto_id,
481                                            UINT32 mx_chan_id)
482 {
483     tBTM_SEC_SERV_REC   *p_srec;
484     UINT16               index;
485     UINT16               first_unused_record = BTM_NO_AVAIL_SEC_SERVICES;
486     BOOLEAN              record_allocated = FALSE;
487     BOOLEAN              is_originator;
488 #if (L2CAP_UCD_INCLUDED == TRUE)
489     BOOLEAN              is_ucd;
490
491     if (conn_type & CONNECTION_TYPE_ORIG_MASK)
492         is_originator = TRUE;
493     else
494         is_originator = FALSE;
495
496     if (conn_type & CONNECTION_TYPE_CONNLESS_MASK )
497     {
498         is_ucd = TRUE;
499     }
500     else
501     {
502         is_ucd = FALSE;
503     }
504 #else
505     is_originator = conn_type;
506 #endif
507
508     /* See if the record can be reused (same service name, psm, mx_proto_id,
509        service_id, and mx_chan_id), or obtain the next unused record */
510
511     p_srec = &btm_cb.sec_serv_rec[0];
512
513
514     for (index = 0; index < BTM_SEC_MAX_SERVICE_RECORDS; index++, p_srec++)
515     {
516         /* Check if there is already a record for this service */
517         if (p_srec->security_flags & BTM_SEC_IN_USE)
518         {
519 #if BTM_SEC_SERVICE_NAME_LEN > 0
520             if (p_srec->psm == psm                  &&
521                 p_srec->mx_proto_id == mx_proto_id  &&
522                 service_id == p_srec->service_id    &&
523                 (!strncmp (p_name, (char *) p_srec->orig_service_name,
524                            BTM_SEC_SERVICE_NAME_LEN) ||
525                  !strncmp (p_name, (char *) p_srec->term_service_name,
526                            BTM_SEC_SERVICE_NAME_LEN)))
527 #else
528             if (p_srec->psm == psm                  &&
529                 p_srec->mx_proto_id == mx_proto_id  &&
530                 service_id == p_srec->service_id)
531 #endif
532             {
533                 record_allocated = TRUE;
534                 break;
535             }
536         }
537         /* Mark the first available service record */
538         else if (!record_allocated)
539         {
540             memset (p_srec, 0, sizeof(tBTM_SEC_SERV_REC));
541             record_allocated = TRUE;
542             first_unused_record = index;
543         }
544     }
545
546     if (!record_allocated)
547     {
548         BTM_TRACE_WARNING("BTM_SEC_REG: Out of Service Records (%d)",  BTM_SEC_MAX_SERVICE_RECORDS);
549         return(record_allocated);
550     }
551
552     /* Process the request if service record is valid */
553     /* If a duplicate service wasn't found, use the first available */
554     if (index >= BTM_SEC_MAX_SERVICE_RECORDS)
555     {
556         index = first_unused_record;
557         p_srec = &btm_cb.sec_serv_rec[index];
558     }
559
560     p_srec->psm         = psm;
561     p_srec->service_id  = service_id;
562     p_srec->mx_proto_id = mx_proto_id;
563
564     if (is_originator)
565     {
566         p_srec->orig_mx_chan_id = mx_chan_id;
567 #if BTM_SEC_SERVICE_NAME_LEN > 0
568         BCM_STRNCPY_S ((char *)p_srec->orig_service_name, sizeof(p_srec->orig_service_name), p_name, BTM_SEC_SERVICE_NAME_LEN);
569 #endif
570         /* clear out the old setting, just in case it exists */
571 #if (L2CAP_UCD_INCLUDED == TRUE)
572         if ( is_ucd )
573         {
574             p_srec->ucd_security_flags &=
575             ~(BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT    | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM |
576               BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE);
577         }
578         else
579 #endif
580         {
581             p_srec->security_flags &=
582             ~(BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT    | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM |
583               BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE);
584         }
585
586         /* Parameter validation.  Originator should not set requirements for incoming connections */
587         sec_level &= ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM);
588
589         if (btm_cb.security_mode == BTM_SEC_MODE_SP ||
590             btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
591             btm_cb.security_mode == BTM_SEC_MODE_SC)
592         {
593             if (sec_level & BTM_SEC_OUT_AUTHENTICATE)
594                 sec_level |= BTM_SEC_OUT_MITM;
595         }
596
597         /* Make sure the authenticate bit is set, when encrypt bit is set */
598         if (sec_level & BTM_SEC_OUT_ENCRYPT)
599             sec_level |= BTM_SEC_OUT_AUTHENTICATE;
600
601         /* outgoing connections usually set the security level right before
602          * the connection is initiated.
603          * set it to be the outgoing service */
604 #if (L2CAP_UCD_INCLUDED == TRUE)
605         if ( is_ucd == FALSE )
606 #endif
607         {
608             btm_cb.p_out_serv = p_srec;
609         }
610     }
611     else
612     {
613         p_srec->term_mx_chan_id = mx_chan_id;
614 #if BTM_SEC_SERVICE_NAME_LEN > 0
615         BCM_STRNCPY_S ((char *)p_srec->term_service_name, sizeof(p_srec->term_service_name), p_name, BTM_SEC_SERVICE_NAME_LEN);
616 #endif
617         /* clear out the old setting, just in case it exists */
618 #if (L2CAP_UCD_INCLUDED == TRUE)
619         if ( is_ucd )
620         {
621             p_srec->ucd_security_flags &=
622             ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT     | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM |
623               BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE);
624         }
625         else
626 #endif
627         {
628             p_srec->security_flags &=
629             ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT     | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM |
630               BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE);
631         }
632
633         /* Parameter validation.  Acceptor should not set requirements for outgoing connections */
634         sec_level &= ~(BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM);
635
636         if (btm_cb.security_mode == BTM_SEC_MODE_SP ||
637             btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
638             btm_cb.security_mode == BTM_SEC_MODE_SC)
639         {
640             if (sec_level & BTM_SEC_IN_AUTHENTICATE)
641                 sec_level |= BTM_SEC_IN_MITM;
642         }
643
644         /* Make sure the authenticate bit is set, when encrypt bit is set */
645         if (sec_level & BTM_SEC_IN_ENCRYPT)
646             sec_level |= BTM_SEC_IN_AUTHENTICATE;
647     }
648
649 #if (L2CAP_UCD_INCLUDED == TRUE)
650     if ( is_ucd )
651     {
652         p_srec->security_flags     |= (UINT16)(BTM_SEC_IN_USE);
653         p_srec->ucd_security_flags |= (UINT16)(sec_level | BTM_SEC_IN_USE);
654     }
655     else
656     {
657         p_srec->security_flags |= (UINT16)(sec_level | BTM_SEC_IN_USE);
658     }
659
660     BTM_TRACE_API("BTM_SEC_REG[%d]: id %d, conn_type 0x%x, psm 0x%04x, proto_id %d, chan_id %d",
661                    index, service_id, conn_type, psm, mx_proto_id, mx_chan_id);
662
663     BTM_TRACE_API("               : security_flags: 0x%04x, ucd_security_flags: 0x%04x",
664                    p_srec->security_flags, p_srec->ucd_security_flags);
665
666 #if BTM_SEC_SERVICE_NAME_LEN > 0
667     BTM_TRACE_API("               : service name [%s] (up to %d chars saved)",
668                    p_name, BTM_SEC_SERVICE_NAME_LEN);
669 #endif
670 #else
671     p_srec->security_flags |= (UINT16)(sec_level | BTM_SEC_IN_USE);
672
673     BTM_TRACE_API("BTM_SEC_REG[%d]: id %d, is_orig %d, psm 0x%04x, proto_id %d, chan_id %d",
674                    index, service_id, is_originator, psm, mx_proto_id, mx_chan_id);
675
676 #if BTM_SEC_SERVICE_NAME_LEN > 0
677     BTM_TRACE_API("               : sec: 0x%x, service name [%s] (up to %d chars saved)",
678                    p_srec->security_flags, p_name, BTM_SEC_SERVICE_NAME_LEN);
679 #endif
680 #endif
681
682
683     return(record_allocated);
684 }
685
686 /*******************************************************************************
687 **
688 ** Function         BTM_SecClrService
689 **
690 ** Description      Removes specified service record(s) from the security database.
691 **                  All service records with the specified name are removed.
692 **                  Typically used only by devices with limited RAM so that it can
693 **                  reuse an old security service record.
694 **
695 **                  Note: Unpredictable results may occur if a service is cleared
696 **                      that is still in use by an application/profile.
697 **
698 ** Parameters       Service ID - Id of the service to remove. ('0' removes all service
699 **                          records (except SDP).
700 **
701 ** Returns          Number of records that were freed.
702 **
703 *******************************************************************************/
704 UINT8 BTM_SecClrService (UINT8 service_id)
705 {
706     tBTM_SEC_SERV_REC   *p_srec = &btm_cb.sec_serv_rec[0];
707     UINT8   num_freed = 0;
708     int     i;
709
710     for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++)
711     {
712         /* Delete services with specified name (if in use and not SDP) */
713         if ((p_srec->security_flags & BTM_SEC_IN_USE) && (p_srec->psm != BT_PSM_SDP) &&
714             (!service_id || (service_id == p_srec->service_id)))
715         {
716             BTM_TRACE_API("BTM_SEC_CLR[%d]: id %d", i, service_id);
717             p_srec->security_flags = 0;
718 #if (L2CAP_UCD_INCLUDED == TRUE)
719             p_srec->ucd_security_flags = 0;
720 #endif
721             num_freed++;
722         }
723     }
724
725     return(num_freed);
726 }
727
728 /*******************************************************************************
729 **
730 ** Function         btm_sec_clr_service_by_psm
731 **
732 ** Description      Removes specified service record from the security database.
733 **                  All service records with the specified psm are removed.
734 **                  Typically used by L2CAP to free up the service record used
735 **                  by dynamic PSM clients when the channel is closed.
736 **                  The given psm must be a virtual psm.
737 **
738 ** Parameters       Service ID - Id of the service to remove. ('0' removes all service
739 **                          records (except SDP).
740 **
741 ** Returns          Number of records that were freed.
742 **
743 *******************************************************************************/
744 UINT8 btm_sec_clr_service_by_psm (UINT16 psm)
745 {
746     tBTM_SEC_SERV_REC   *p_srec = &btm_cb.sec_serv_rec[0];
747     UINT8   num_freed = 0;
748     int     i;
749
750     for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++)
751     {
752         /* Delete services with specified name (if in use and not SDP) */
753         if ((p_srec->security_flags & BTM_SEC_IN_USE) && (p_srec->psm == psm) )
754         {
755             BTM_TRACE_API("BTM_SEC_CLR[%d]: id %d ", i, p_srec->service_id);
756             p_srec->security_flags = 0;
757             num_freed++;
758         }
759     }
760     BTM_TRACE_API("btm_sec_clr_service_by_psm psm:0x%x num_freed:%d", psm, num_freed);
761
762     return(num_freed);
763 }
764
765 /*******************************************************************************
766 **
767 ** Function         btm_sec_clr_temp_auth_service
768 **
769 ** Description      Removes specified device record's temporary authorization
770 **                  flag from the security database.
771 **
772 ** Parameters       Device address to be cleared
773 **
774 ** Returns          void.
775 **
776 *******************************************************************************/
777 void btm_sec_clr_temp_auth_service (BD_ADDR bda)
778 {
779     tBTM_SEC_DEV_REC   *p_dev_rec;
780
781     if ((p_dev_rec = btm_find_dev (bda)) == NULL)
782     {
783         BTM_TRACE_WARNING ("btm_sec_clr_temp_auth_service() - no dev CB");
784         return;
785     }
786
787     /* Reset the temporary authorized flag so that next time (untrusted) service is accessed autorization will take place */
788     if (p_dev_rec->last_author_service_id != BTM_SEC_NO_LAST_SERVICE_ID && p_dev_rec->p_cur_service)
789     {
790         BTM_TRACE_DEBUG ("btm_sec_clr_auth_service_by_psm [clearing device: %02x:%02x:%02x:%02x:%02x:%02x]",
791                     bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
792
793         p_dev_rec->last_author_service_id = BTM_SEC_NO_LAST_SERVICE_ID;
794     }
795 }
796
797 /*******************************************************************************
798 **
799 ** Function         BTM_PINCodeReply
800 **
801 ** Description      This function is called after Security Manager submitted
802 **                  PIN code request to the UI.
803 **
804 ** Parameters:      bd_addr      - Address of the device for which PIN was requested
805 **                  res          - result of the operation BTM_SUCCESS if success
806 **                  pin_len      - length in bytes of the PIN Code
807 **                  p_pin        - pointer to array with the PIN Code
808 **                  trusted_mask - bitwise OR of trusted services (array of UINT32)
809 **
810 *******************************************************************************/
811 void BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
812 {
813     tBTM_SEC_DEV_REC *p_dev_rec;
814
815     BTM_TRACE_API ("BTM_PINCodeReply(): PairState: %s   PairFlags: 0x%02x  PinLen:%d  Result:%d",
816                     btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, pin_len, res);
817
818     /* If timeout already expired or has been canceled, ignore the reply */
819     if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN)
820     {
821         BTM_TRACE_WARNING ("BTM_PINCodeReply() - Wrong State: %d", btm_cb.pairing_state);
822         return;
823     }
824
825     if (memcmp (bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) != 0)
826     {
827         BTM_TRACE_ERROR ("BTM_PINCodeReply() - Wrong BD Addr");
828         return;
829     }
830
831     if ((p_dev_rec = btm_find_dev (bd_addr)) == NULL)
832     {
833         BTM_TRACE_ERROR ("BTM_PINCodeReply() - no dev CB");
834         return;
835     }
836
837     if ( (pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL) )
838         res = BTM_ILLEGAL_VALUE;
839
840     if (res != BTM_SUCCESS)
841     {
842         /* if peer started dd OR we started dd and pre-fetch pin was not used send negative reply */
843         if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) ||
844             ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
845             (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) )
846         {
847             /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed event */
848             btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
849             btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
850
851             btsnd_hcic_pin_code_neg_reply (bd_addr);
852         }
853         else
854         {
855             p_dev_rec->security_required = BTM_SEC_NONE;
856             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
857         }
858         return;
859     }
860     if (trusted_mask)
861         BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask);
862     p_dev_rec->sec_flags   |= BTM_SEC_LINK_KEY_AUTHED;
863
864     if ( (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
865          &&  (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE)
866          &&  (btm_cb.security_mode_changed == FALSE) )
867     {
868         /* This is start of the dedicated bonding if local device is 2.0 */
869         btm_cb.pin_code_len = pin_len;
870         memcpy (btm_cb.pin_code, p_pin, pin_len);
871
872         btm_cb.security_mode_changed = TRUE;
873 #ifdef APPL_AUTH_WRITE_EXCEPTION
874         if(!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr))
875 #endif
876         btsnd_hcic_write_auth_enable (TRUE);
877
878         btm_cb.acl_disc_reason = 0xff ;
879
880         /* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */
881         /*  before originating  */
882         if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)
883         {
884             BTM_TRACE_WARNING ("BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected incoming connection");
885             /* we change state little bit early so btm_sec_connected() will originate connection */
886             /*   when existing ACL link is down completely */
887             btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
888         }
889         /* if we already accepted incoming connection from pairing device */
890         else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND)
891         {
892             BTM_TRACE_WARNING ("BTM_PINCodeReply(): link is connecting so wait pin code request from peer");
893             btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
894         }
895         else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED)
896         {
897             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
898             p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED;
899
900             if (btm_cb.api.p_auth_complete_callback)
901                 (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,  p_dev_rec->dev_class,
902                                                     p_dev_rec->sec_bd_name, HCI_ERR_AUTH_FAILURE);
903         }
904         return;
905     }
906
907     btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
908     btm_cb.acl_disc_reason = HCI_SUCCESS;
909
910 #ifdef PORCHE_PAIRING_CONFLICT
911     BTM_TRACE_EVENT("BTM_PINCodeReply(): Saving pin_len: %d btm_cb.pin_code_len: %d", pin_len, btm_cb.pin_code_len);
912     /* if this was not pre-fetched, save the PIN */
913     if (btm_cb.pin_code_len == 0)
914         memcpy (btm_cb.pin_code, p_pin, pin_len);
915     btm_cb.pin_code_len_saved = pin_len;
916 #endif
917     btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin);
918 }
919
920 /*******************************************************************************
921 **
922 ** Function         btm_sec_bond_by_transport
923 **
924 ** Description      this is the bond function that will start either SSP or SMP.
925 **
926 ** Parameters:      bd_addr      - Address of the device to bond
927 **                  pin_len      - length in bytes of the PIN Code
928 **                  p_pin        - pointer to array with the PIN Code
929 **                  trusted_mask - bitwise OR of trusted services (array of UINT32)
930 **
931 **  Note: After 2.1 parameters are not used and preserved here not to change API
932 *******************************************************************************/
933 tBTM_STATUS btm_sec_bond_by_transport (BD_ADDR bd_addr, tBT_TRANSPORT transport,
934                                        UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
935 {
936     tBTM_SEC_DEV_REC *p_dev_rec;
937     tBTM_STATUS      status;
938     UINT8            *p_features;
939     UINT8            ii;
940     tACL_CONN        *p= btm_bda_to_acl(bd_addr, transport);
941     BTM_TRACE_API ("btm_sec_bond_by_transport BDA: %02x:%02x:%02x:%02x:%02x:%02x",
942                     bd_addr[0], bd_addr[1], bd_addr[2], bd_addr[3], bd_addr[4], bd_addr[5]);
943
944     BTM_TRACE_DEBUG("btm_sec_bond_by_transport: Transport used %d" , transport);
945
946
947     /* Other security process is in progress */
948     if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
949     {
950         BTM_TRACE_ERROR ("BTM_SecBond: already busy in state: %s", btm_pair_state_descr(btm_cb.pairing_state));
951         return(BTM_WRONG_MODE);
952     }
953
954     if ((p_dev_rec = btm_find_or_alloc_dev (bd_addr)) == NULL)
955     {
956         return(BTM_NO_RESOURCES);
957     }
958
959     BTM_TRACE_DEBUG ("before update sec_flags=0x%x", p_dev_rec->sec_flags);
960
961     /* Finished if connection is active and already paired */
962     if ( ((p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE) && transport == BT_TRANSPORT_BR_EDR
963          &&  (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))
964 #if (BLE_INCLUDED == TRUE)
965         ||((p_dev_rec->ble_hci_handle != BTM_SEC_INVALID_HANDLE) && transport == BT_TRANSPORT_LE
966          &&  (p_dev_rec->sec_flags & BTM_SEC_LE_AUTHENTICATED))
967 #endif
968
969          )
970     {
971         BTM_TRACE_WARNING("BTM_SecBond -> Already Paired");
972         return(BTM_SUCCESS);
973     }
974
975     /* Tell controller to get rid of the link key if it has one stored */
976     if ((BTM_DeleteStoredLinkKey (bd_addr, NULL)) != BTM_SUCCESS)
977         return(BTM_NO_RESOURCES);
978
979     /* Save the PIN code if we got a valid one */
980     if (p_pin && (pin_len <= PIN_CODE_LEN) && (pin_len != 0))
981     {
982         btm_cb.pin_code_len = pin_len;
983         memcpy (btm_cb.pin_code, p_pin, PIN_CODE_LEN);
984     }
985
986     memcpy (btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN);
987
988     btm_cb.pairing_flags = BTM_PAIR_FLAGS_WE_STARTED_DD;
989
990     p_dev_rec->security_required = BTM_SEC_OUT_AUTHENTICATE;
991     p_dev_rec->is_originator     = TRUE;
992     if (trusted_mask)
993         BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask);
994
995 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
996     if (transport == BT_TRANSPORT_LE)
997     {
998         p_dev_rec->sec_flags &= ~ BTM_SEC_LE_MASK;
999
1000         if (SMP_Pair(bd_addr) == SMP_STARTED)
1001         {
1002             btm_cb.pairing_flags |= BTM_PAIR_FLAGS_LE_ACTIVE;
1003             p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
1004             btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
1005             return BTM_CMD_STARTED;
1006         }
1007
1008         btm_cb.pairing_flags = 0;
1009         return(BTM_NO_RESOURCES);
1010     }
1011 #endif
1012
1013     p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED
1014                                   | BTM_SEC_ROLE_SWITCHED  | BTM_SEC_LINK_KEY_AUTHED);
1015
1016
1017     BTM_TRACE_DEBUG ("after update sec_flags=0x%x", p_dev_rec->sec_flags);
1018     if (!controller_get_interface()->supports_simple_pairing())
1019     {
1020         /* The special case when we authenticate keyboard.  Set pin type to fixed */
1021         /* It would be probably better to do it from the application, but it is */
1022         /* complicated */
1023         if (((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL)
1024             && (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD)
1025             && (btm_cb.cfg.pin_type != HCI_PIN_TYPE_FIXED))
1026         {
1027             btm_cb.pin_type_changed = TRUE;
1028             btsnd_hcic_write_pin_type (HCI_PIN_TYPE_FIXED);
1029         }
1030     }
1031
1032     for (ii = 0; ii <= HCI_EXT_FEATURES_PAGE_MAX; ii++)
1033     {
1034         p_features = p_dev_rec->features[ii];
1035         BTM_TRACE_EVENT("  remote_features page[%1d] = %02x-%02x-%02x-%02x",
1036                          ii, p_features[0], p_features[1], p_features[2], p_features[3]);
1037         BTM_TRACE_EVENT("                              %02x-%02x-%02x-%02x",
1038                              p_features[4], p_features[5], p_features[6], p_features[7]);
1039     }
1040
1041     BTM_TRACE_EVENT ("BTM_SecBond: Remote sm4: 0x%x  HCI Handle: 0x%04x", p_dev_rec->sm4, p_dev_rec->hci_handle);
1042
1043 #if BTM_SEC_FORCE_RNR_FOR_DBOND == TRUE
1044     p_dev_rec->sec_flags &= ~BTM_SEC_NAME_KNOWN;
1045 #endif
1046
1047     /* If connection already exists... */
1048     if (p && p->hci_handle != BTM_SEC_INVALID_HANDLE)
1049     {
1050         if (!btm_sec_start_authentication (p_dev_rec))
1051             return(BTM_NO_RESOURCES);
1052
1053         btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
1054
1055         /* Mark lcb as bonding */
1056         l2cu_update_lcb_4_bonding (bd_addr, TRUE);
1057         return(BTM_CMD_STARTED);
1058     }
1059
1060     BTM_TRACE_DEBUG ("sec mode: %d sm4:x%x", btm_cb.security_mode, p_dev_rec->sm4);
1061     if (!controller_get_interface()->supports_simple_pairing()
1062         || (p_dev_rec->sm4 == BTM_SM4_KNOWN))
1063     {
1064         if ( btm_sec_check_prefetch_pin (p_dev_rec) )
1065             return (BTM_CMD_STARTED);
1066     }
1067     if ((btm_cb.security_mode == BTM_SEC_MODE_SP ||
1068          btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
1069          btm_cb.security_mode == BTM_SEC_MODE_SC) &&
1070          BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4))
1071     {
1072         /* local is 2.1 and peer is unknown */
1073         if ((p_dev_rec->sm4 & BTM_SM4_CONN_PEND) == 0)
1074         {
1075             /* we are not accepting connection request from peer
1076              * -> RNR (to learn if peer is 2.1)
1077              * RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */
1078             btm_sec_change_pairing_state (BTM_PAIR_STATE_GET_REM_NAME);
1079             BTM_ReadRemoteDeviceName(bd_addr, NULL, BT_TRANSPORT_BR_EDR);
1080         }
1081         else
1082         {
1083             /* We are accepting connection request from peer */
1084             btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
1085         }
1086         BTM_TRACE_DEBUG ("State:%s sm4: 0x%x sec_state:%d",
1087             btm_pair_state_descr (btm_cb.pairing_state), p_dev_rec->sm4, p_dev_rec->sec_state);
1088         return BTM_CMD_STARTED;
1089     }
1090
1091     /* both local and peer are 2.1  */
1092     status = btm_sec_dd_create_conn(p_dev_rec);
1093
1094     if (status != BTM_CMD_STARTED)
1095     {
1096         btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
1097     }
1098
1099     return status;
1100 }
1101
1102 /*******************************************************************************
1103 **
1104 ** Function         BTM_SecBondByTransport
1105 **
1106 ** Description      This function is called to perform bonding with peer device.
1107 **                  If the connection is already up, but not secure, pairing
1108 **                  is attempted.  If already paired BTM_SUCCESS is returned.
1109 **
1110 ** Parameters:      bd_addr      - Address of the device to bond
1111 **                  transport    - doing SSP over BR/EDR or SMP over LE
1112 **                  pin_len      - length in bytes of the PIN Code
1113 **                  p_pin        - pointer to array with the PIN Code
1114 **                  trusted_mask - bitwise OR of trusted services (array of UINT32)
1115 **
1116 **  Note: After 2.1 parameters are not used and preserved here not to change API
1117 *******************************************************************************/
1118 tBTM_STATUS BTM_SecBondByTransport (BD_ADDR bd_addr, tBT_TRANSPORT transport,
1119                                     UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
1120 {
1121 #if SMP_INCLUDED == TRUE
1122     tBT_DEVICE_TYPE     dev_type;
1123     tBLE_ADDR_TYPE      addr_type;
1124
1125     BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type);
1126     /* LE device, do SMP pairing */
1127     if ((transport == BT_TRANSPORT_LE && (dev_type & BT_DEVICE_TYPE_BLE) == 0) ||
1128         (transport == BT_TRANSPORT_BR_EDR && (dev_type & BT_DEVICE_TYPE_BREDR) == 0))
1129     {
1130         return BTM_ILLEGAL_ACTION;
1131     }
1132 #endif
1133     return btm_sec_bond_by_transport(bd_addr, transport, pin_len, p_pin, trusted_mask);
1134 }
1135
1136 /*******************************************************************************
1137 **
1138 ** Function         BTM_SecBond
1139 **
1140 ** Description      This function is called to perform bonding with peer device.
1141 **                  If the connection is already up, but not secure, pairing
1142 **                  is attempted.  If already paired BTM_SUCCESS is returned.
1143 **
1144 ** Parameters:      bd_addr      - Address of the device to bond
1145 **                  pin_len      - length in bytes of the PIN Code
1146 **                  p_pin        - pointer to array with the PIN Code
1147 **                  trusted_mask - bitwise OR of trusted services (array of UINT32)
1148 **
1149 **  Note: After 2.1 parameters are not used and preserved here not to change API
1150 *******************************************************************************/
1151 tBTM_STATUS BTM_SecBond (BD_ADDR bd_addr, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
1152 {
1153     tBT_TRANSPORT   transport = BT_TRANSPORT_BR_EDR;
1154 #if BLE_INCLUDED == TRUE
1155     if (BTM_UseLeLink(bd_addr))
1156         transport = BT_TRANSPORT_LE;
1157 #endif
1158     return btm_sec_bond_by_transport(bd_addr, transport, pin_len, p_pin, trusted_mask);
1159 }
1160 /*******************************************************************************
1161 **
1162 ** Function         BTM_SecBondCancel
1163 **
1164 ** Description      This function is called to cancel ongoing bonding process
1165 **                  with peer device.
1166 **
1167 ** Parameters:      bd_addr      - Address of the peer device
1168 **                         transport    - FALSE for BR/EDR link; TRUE for LE link
1169 **
1170 *******************************************************************************/
1171 tBTM_STATUS BTM_SecBondCancel (BD_ADDR bd_addr)
1172 {
1173     tBTM_SEC_DEV_REC *p_dev_rec;
1174
1175     BTM_TRACE_API ("BTM_SecBondCancel()  State: %s flags:0x%x",
1176                     btm_pair_state_descr (btm_cb.pairing_state), btm_cb.pairing_flags);
1177
1178     if (((p_dev_rec = btm_find_dev (bd_addr)) == NULL)
1179         ||  (memcmp (btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN) != 0) )
1180         return BTM_UNKNOWN_ADDR;
1181
1182 #if SMP_INCLUDED == TRUE
1183     if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE)
1184     {
1185         if (p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING)
1186         {
1187             BTM_TRACE_DEBUG ("Cancel LE pairing");
1188             if (SMP_PairCancel(bd_addr))
1189             {
1190                 return BTM_CMD_STARTED;
1191             }
1192         }
1193         return BTM_WRONG_MODE;
1194     }
1195
1196 #endif
1197     BTM_TRACE_DEBUG ("hci_handle:0x%x sec_state:%d", p_dev_rec->hci_handle, p_dev_rec->sec_state );
1198     if (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_cb.pairing_state &&
1199         BTM_PAIR_FLAGS_WE_STARTED_DD & btm_cb.pairing_flags)
1200     {
1201         /* pre-fetching pin for dedicated bonding */
1202         btm_sec_bond_cancel_complete();
1203         return BTM_SUCCESS;
1204     }
1205
1206     /* If this BDA is in a bonding procedure */
1207     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
1208          &&  (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD))
1209     {
1210         /* If the HCI link is up */
1211         if (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)
1212         {
1213             /* If some other thread disconnecting, we do not send second command */
1214             if ((p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING) ||
1215                 (p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH))
1216                 return(BTM_CMD_STARTED);
1217
1218             /* If the HCI link was set up by Bonding process */
1219             if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)
1220                 return btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle);
1221             else
1222                 l2cu_update_lcb_4_bonding(bd_addr, FALSE);
1223
1224             return BTM_NOT_AUTHORIZED;
1225         }
1226         else /*HCI link is not up */
1227         {
1228             /* If the HCI link creation was started by Bonding process */
1229             if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)
1230             {
1231                 if (btsnd_hcic_create_conn_cancel(bd_addr))
1232                     return BTM_CMD_STARTED;
1233
1234                 return BTM_NO_RESOURCES;
1235             }
1236             if (btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME)
1237             {
1238                 BTM_CancelRemoteDeviceName();
1239                 btm_cb.pairing_flags |= BTM_PAIR_FLAGS_WE_CANCEL_DD;
1240                 return BTM_CMD_STARTED;
1241             }
1242             return BTM_NOT_AUTHORIZED;
1243         }
1244     }
1245
1246     return BTM_WRONG_MODE;
1247 }
1248
1249 /*******************************************************************************
1250 **
1251 ** Function         BTM_SecGetDeviceLinkKey
1252 **
1253 ** Description      This function is called to obtain link key for the device
1254 **                  it returns BTM_SUCCESS if link key is available, or
1255 **                  BTM_UNKNOWN_ADDR if Security Manager does not know about
1256 **                  the device or device record does not contain link key info
1257 **
1258 ** Parameters:      bd_addr      - Address of the device
1259 **                  link_key     - Link Key is copied into this array
1260 **
1261 *******************************************************************************/
1262 tBTM_STATUS BTM_SecGetDeviceLinkKey (BD_ADDR bd_addr, LINK_KEY link_key)
1263 {
1264     tBTM_SEC_DEV_REC *p_dev_rec;
1265
1266     if (((p_dev_rec = btm_find_dev (bd_addr)) != NULL)
1267         && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN))
1268     {
1269         memcpy (link_key, p_dev_rec->link_key, LINK_KEY_LEN);
1270         return(BTM_SUCCESS);
1271     }
1272     return(BTM_UNKNOWN_ADDR);
1273 }
1274
1275 /*******************************************************************************
1276 **
1277 ** Function         BTM_SecGetDeviceLinkKeyType
1278 **
1279 ** Description      This function is called to obtain link key type for the
1280 **                  device.
1281 **                  it returns BTM_SUCCESS if link key is available, or
1282 **                  BTM_UNKNOWN_ADDR if Security Manager does not know about
1283 **                  the device or device record does not contain link key info
1284 **
1285 ** Returns          BTM_LKEY_TYPE_IGNORE if link key is unknown, link type
1286 **                  otherwise.
1287 **
1288 *******************************************************************************/
1289 tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType (BD_ADDR bd_addr)
1290 {
1291     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bd_addr);
1292
1293     if ((p_dev_rec != NULL) && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN))
1294     {
1295         return p_dev_rec->link_key_type;
1296     }
1297     return BTM_LKEY_TYPE_IGNORE;
1298 }
1299
1300 /*******************************************************************************
1301 **
1302 ** Function         BTM_SetEncryption
1303 **
1304 ** Description      This function is called to ensure that connection is
1305 **                  encrypted.  Should be called only on an open connection.
1306 **                  Typically only needed for connections that first want to
1307 **                  bring up unencrypted links, then later encrypt them.
1308 **
1309 ** Parameters:      bd_addr       - Address of the peer device
1310 **                  p_callback    - Pointer to callback function called if
1311 **                                  this function returns PENDING after required
1312 **                                  procedures are completed.  Can be set to NULL
1313 **                                  if status is not desired.
1314 **                  p_ref_data    - pointer to any data the caller wishes to receive
1315 **                                  in the callback function upon completion.
1316 *                                   can be set to NULL if not used.
1317 **                  transport  -    TRUE to encryption the link over LE transport
1318 **                                  or FALSE for BR/EDR transport
1319 **
1320 ** Returns          BTM_SUCCESS   - already encrypted
1321 **                  BTM_PENDING   - command will be returned in the callback
1322 **                  BTM_WRONG_MODE- connection not up.
1323 **                  BTM_BUSY      - security procedures are currently active
1324 **                  BTM_MODE_UNSUPPORTED - if security manager not linked in.
1325 **
1326 *******************************************************************************/
1327 tBTM_STATUS BTM_SetEncryption (BD_ADDR bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CBACK *p_callback,
1328                                void *p_ref_data)
1329 {
1330     tBTM_STATUS rc = 0;
1331
1332     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (bd_addr);
1333     if (!p_dev_rec ||
1334         (transport == BT_TRANSPORT_BR_EDR && p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE)
1335 #if BLE_INCLUDED == TRUE
1336         || (transport == BT_TRANSPORT_LE && p_dev_rec->ble_hci_handle == BTM_SEC_INVALID_HANDLE)
1337 #endif
1338         )
1339     {
1340         /* Connection should be up and runnning */
1341         BTM_TRACE_WARNING ("Security Manager: BTM_SetEncryption not connected");
1342
1343         if (p_callback)
1344             (*p_callback) (bd_addr, transport, p_ref_data, BTM_WRONG_MODE);
1345
1346         return(BTM_WRONG_MODE);
1347     }
1348
1349     if ((transport == BT_TRANSPORT_BR_EDR &&
1350          (p_dev_rec->sec_flags &  BTM_SEC_ENCRYPTED))
1351 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
1352          || (transport == BT_TRANSPORT_LE &&
1353            (p_dev_rec->sec_flags & BTM_SEC_LE_ENCRYPTED))
1354 #endif
1355           )
1356     {
1357         BTM_TRACE_EVENT ("Security Manager: BTM_SetEncryption already encrypted");
1358
1359         if (p_callback)
1360             (*p_callback) (bd_addr, transport, p_ref_data, BTM_SUCCESS);
1361
1362         return(BTM_SUCCESS);
1363     }
1364
1365     /* enqueue security request if security is active */
1366     if (p_dev_rec->p_callback || (p_dev_rec->sec_state != BTM_SEC_STATE_IDLE))
1367     {
1368         BTM_TRACE_WARNING ("Security Manager: BTM_SetEncryption busy, enqueue request");
1369
1370         if (btm_sec_queue_encrypt_request(bd_addr, transport, p_callback, p_ref_data))
1371         {
1372             return BTM_CMD_STARTED;
1373         }
1374         else
1375         {
1376             if (p_callback)
1377                 (*p_callback) (bd_addr, transport, p_ref_data, BTM_NO_RESOURCES);
1378             return BTM_NO_RESOURCES;
1379         }
1380     }
1381
1382     p_dev_rec->p_callback        = p_callback;
1383     p_dev_rec->p_ref_data        = p_ref_data;
1384     p_dev_rec->security_required |= (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT);
1385     p_dev_rec->is_originator     = FALSE;
1386
1387     BTM_TRACE_API ("Security Manager: BTM_SetEncryption Handle:%d State:%d Flags:0x%x Required:0x%x",
1388                     p_dev_rec->hci_handle, p_dev_rec->sec_state, p_dev_rec->sec_flags,
1389                     p_dev_rec->security_required);
1390
1391 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
1392     if (transport == BT_TRANSPORT_LE)
1393     {
1394         tACL_CONN *p = btm_bda_to_acl(bd_addr, transport);
1395         if (p)
1396         {
1397            rc = btm_ble_set_encryption(bd_addr, p_ref_data, p->link_role);
1398         }
1399         else
1400         {
1401             rc = BTM_WRONG_MODE;
1402             BTM_TRACE_WARNING("%s: cannot call btm_ble_set_encryption, p is NULL", __FUNCTION__);
1403         }
1404     }
1405     else
1406 #endif
1407         rc = btm_sec_execute_procedure (p_dev_rec);
1408
1409     if (rc != BTM_CMD_STARTED && rc != BTM_BUSY)
1410     {
1411         if (p_callback)
1412         {
1413             p_dev_rec->p_callback = NULL;
1414             (*p_callback) (bd_addr, transport, p_dev_rec->p_ref_data, rc);
1415         }
1416     }
1417
1418     return(rc);
1419 }
1420
1421 /*******************************************************************************
1422  * disconnect the ACL link, if it's not done yet.
1423 *******************************************************************************/
1424 static tBTM_STATUS btm_sec_send_hci_disconnect (tBTM_SEC_DEV_REC *p_dev_rec, UINT8 reason, UINT16 conn_handle)
1425 {
1426     UINT8       old_state = p_dev_rec->sec_state;
1427     tBTM_STATUS status = BTM_CMD_STARTED;
1428
1429     BTM_TRACE_EVENT ("btm_sec_send_hci_disconnect:  handle:0x%x, reason=0x%x",
1430                       conn_handle, reason);
1431
1432     /* send HCI_Disconnect on a transport only once */
1433     switch (old_state)
1434     {
1435         case BTM_SEC_STATE_DISCONNECTING:
1436             if (conn_handle == p_dev_rec->hci_handle)
1437                 return status;
1438
1439             p_dev_rec->sec_state = BTM_SEC_STATE_DISCONNECTING_BOTH;
1440             break;
1441
1442 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
1443         case BTM_SEC_STATE_DISCONNECTING_BLE:
1444             if (conn_handle == p_dev_rec->ble_hci_handle)
1445                 return status;
1446
1447             p_dev_rec->sec_state = BTM_SEC_STATE_DISCONNECTING_BOTH;
1448             break;
1449
1450         case BTM_SEC_STATE_DISCONNECTING_BOTH:
1451             return status;
1452 #endif
1453
1454         default:
1455             p_dev_rec->sec_state = (conn_handle == p_dev_rec->hci_handle) ?
1456                     BTM_SEC_STATE_DISCONNECTING : BTM_SEC_STATE_DISCONNECTING_BLE;
1457
1458             break;
1459     }
1460
1461     /* If a role switch is in progress, delay the HCI Disconnect to avoid controller problem */
1462     if (p_dev_rec->rs_disc_pending == BTM_SEC_RS_PENDING && p_dev_rec->hci_handle == conn_handle)
1463     {
1464         BTM_TRACE_DEBUG("RS in progress - Set DISC Pending flag in btm_sec_send_hci_disconnect to delay disconnect");
1465               p_dev_rec->rs_disc_pending = BTM_SEC_DISC_PENDING;
1466         status = BTM_SUCCESS;
1467     }
1468     /* Tear down the HCI link */
1469     else if (!btsnd_hcic_disconnect (conn_handle, reason))
1470     {
1471          /* could not send disconnect. restore old state */
1472          p_dev_rec->sec_state = old_state;
1473          status = BTM_NO_RESOURCES;
1474     }
1475
1476     return status;
1477 }
1478
1479 /*******************************************************************************
1480 **
1481 ** Function         BTM_ConfirmReqReply
1482 **
1483 ** Description      This function is called to confirm the numeric value for
1484 **                  Simple Pairing in response to BTM_SP_CFM_REQ_EVT
1485 **
1486 ** Parameters:      res           - result of the operation BTM_SUCCESS if success
1487 **                  bd_addr       - Address of the peer device
1488 **
1489 *******************************************************************************/
1490 void BTM_ConfirmReqReply(tBTM_STATUS res, BD_ADDR bd_addr)
1491 {
1492     tBTM_SEC_DEV_REC *p_dev_rec;
1493
1494     BTM_TRACE_EVENT ("BTM_ConfirmReqReply() State: %s  Res: %u",
1495                       btm_pair_state_descr(btm_cb.pairing_state), res);
1496
1497     /* If timeout already expired or has been canceled, ignore the reply */
1498     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM)
1499          ||  (memcmp (btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN) != 0) )
1500         return;
1501
1502     btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
1503
1504     if ( (res == BTM_SUCCESS) || (res == BTM_SUCCESS_NO_SECURITY) )
1505     {
1506         btm_cb.acl_disc_reason = HCI_SUCCESS;
1507
1508         if (res == BTM_SUCCESS)
1509         {
1510             if ((p_dev_rec = btm_find_dev (bd_addr)) != NULL)
1511                 p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED;
1512         }
1513
1514         btsnd_hcic_user_conf_reply (bd_addr, TRUE);
1515     }
1516     else
1517     {
1518         /* Report authentication failed event from state BTM_PAIR_STATE_WAIT_AUTH_COMPLETE */
1519         btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
1520         btsnd_hcic_user_conf_reply (bd_addr, FALSE);
1521     }
1522 }
1523
1524 /*******************************************************************************
1525 **
1526 ** Function         BTM_PasskeyReqReply
1527 **
1528 ** Description      This function is called to provide the passkey for
1529 **                  Simple Pairing in response to BTM_SP_KEY_REQ_EVT
1530 **
1531 ** Parameters:      res     - result of the operation BTM_SUCCESS if success
1532 **                  bd_addr - Address of the peer device
1533 **                  passkey - numeric value in the range of
1534 **                  BTM_MIN_PASSKEY_VAL(0) - BTM_MAX_PASSKEY_VAL(999999(0xF423F)).
1535 **
1536 *******************************************************************************/
1537 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
1538 void BTM_PasskeyReqReply(tBTM_STATUS res, BD_ADDR bd_addr, UINT32 passkey)
1539 {
1540     BTM_TRACE_API ("BTM_PasskeyReqReply: State: %s  res:%d",
1541                     btm_pair_state_descr(btm_cb.pairing_state), res);
1542
1543     if ( (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
1544          ||  (memcmp (btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN) != 0) )
1545     {
1546         return;
1547     }
1548
1549     /* If timeout already expired or has been canceled, ignore the reply */
1550     if ( (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) && (res != BTM_SUCCESS) )
1551     {
1552         tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bd_addr);
1553         if (p_dev_rec != NULL)
1554         {
1555             btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
1556
1557             if (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)
1558                 btm_sec_send_hci_disconnect (p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle);
1559             else
1560                 BTM_SecBondCancel(bd_addr);
1561
1562             p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_LINK_KEY_KNOWN);
1563
1564             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
1565             return;
1566         }
1567     }
1568     else if (btm_cb.pairing_state != BTM_PAIR_STATE_KEY_ENTRY)
1569         return;
1570
1571     if (passkey > BTM_MAX_PASSKEY_VAL)
1572         res = BTM_ILLEGAL_VALUE;
1573
1574     btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
1575
1576     if (res != BTM_SUCCESS)
1577     {
1578         /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed event */
1579         btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
1580         btsnd_hcic_user_passkey_neg_reply (bd_addr);
1581     } else {
1582         btm_cb.acl_disc_reason = HCI_SUCCESS;
1583         btsnd_hcic_user_passkey_reply (bd_addr, passkey);
1584     }
1585 }
1586 #endif
1587
1588 /*******************************************************************************
1589 **
1590 ** Function         BTM_SendKeypressNotif
1591 **
1592 ** Description      This function is used during the passkey entry model
1593 **                  by a device with KeyboardOnly IO capabilities
1594 **                  (very likely to be a HID Device).
1595 **                  It is called by a HID Device to inform the remote device when
1596 **                  a key has been entered or erased.
1597 **
1598 ** Parameters:      bd_addr - Address of the peer device
1599 **                  type - notification type
1600 **
1601 *******************************************************************************/
1602 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
1603 void BTM_SendKeypressNotif(BD_ADDR bd_addr, tBTM_SP_KEY_TYPE type)
1604 {
1605     /* This API only make sense between PASSKEY_REQ and SP complete */
1606     if (btm_cb.pairing_state == BTM_PAIR_STATE_KEY_ENTRY)
1607         btsnd_hcic_send_keypress_notif (bd_addr, type);
1608 }
1609 #endif
1610
1611 #if BTM_OOB_INCLUDED == TRUE
1612 /*******************************************************************************
1613 **
1614 ** Function         BTM_IoCapRsp
1615 **
1616 ** Description      This function is called in response to BTM_SP_IO_REQ_EVT
1617 **                  When the event data io_req.oob_data is set to BTM_OOB_UNKNOWN
1618 **                  by the tBTM_SP_CALLBACK implementation, this function is
1619 **                  called to provide the actual response
1620 **
1621 ** Parameters:      bd_addr - Address of the peer device
1622 **                  io_cap  - The IO capability of local device.
1623 **                  oob     - BTM_OOB_NONE or BTM_OOB_PRESENT.
1624 **                  auth_req- MITM protection required or not.
1625 **
1626 *******************************************************************************/
1627 void BTM_IoCapRsp(BD_ADDR bd_addr, tBTM_IO_CAP io_cap, tBTM_OOB_DATA oob, tBTM_AUTH_REQ auth_req)
1628 {
1629     BTM_TRACE_EVENT ("BTM_IoCapRsp: state: %s  oob: %d io_cap: %d",
1630                       btm_pair_state_descr(btm_cb.pairing_state), oob, io_cap);
1631
1632     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS)
1633          ||  (memcmp (btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN) != 0) )
1634         return;
1635
1636     if (oob < BTM_OOB_UNKNOWN && io_cap < BTM_IO_CAP_MAX)
1637     {
1638         btm_cb.devcb.loc_auth_req   = auth_req;
1639         btm_cb.devcb.loc_io_caps    = io_cap;
1640
1641         if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
1642             auth_req = (BTM_AUTH_DD_BOND | (auth_req&BTM_AUTH_YN_BIT));
1643
1644         btsnd_hcic_io_cap_req_reply (bd_addr, io_cap, oob, auth_req);
1645     }
1646 }
1647
1648 /*******************************************************************************
1649 **
1650 ** Function         BTM_ReadLocalOobData
1651 **
1652 ** Description      This function is called to read the local OOB data from
1653 **                  LM
1654 **
1655 *******************************************************************************/
1656 tBTM_STATUS BTM_ReadLocalOobData(void)
1657 {
1658     tBTM_STATUS status = BTM_SUCCESS;
1659
1660     if (btsnd_hcic_read_local_oob_data() == FALSE)
1661         status = BTM_NO_RESOURCES;
1662
1663     return status;
1664 }
1665
1666 /*******************************************************************************
1667 **
1668 ** Function         BTM_RemoteOobDataReply
1669 **
1670 ** Description      This function is called to provide the remote OOB data for
1671 **                  Simple Pairing in response to BTM_SP_RMT_OOB_EVT
1672 **
1673 ** Parameters:      bd_addr     - Address of the peer device
1674 **                  c           - simple pairing Hash C.
1675 **                  r           - simple pairing Randomizer  C.
1676 **
1677 *******************************************************************************/
1678 void BTM_RemoteOobDataReply(tBTM_STATUS res, BD_ADDR bd_addr, BT_OCTET16 c, BT_OCTET16 r)
1679 {
1680     BTM_TRACE_EVENT ("%s() - State: %s res: %d", __func__,
1681                       btm_pair_state_descr(btm_cb.pairing_state), res);
1682
1683     /* If timeout already expired or has been canceled, ignore the reply */
1684     if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP)
1685         return;
1686
1687     btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
1688
1689     if (res != BTM_SUCCESS)
1690     {
1691         /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed event */
1692         btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
1693         btsnd_hcic_rem_oob_neg_reply (bd_addr);
1694     } else {
1695         btm_cb.acl_disc_reason = HCI_SUCCESS;
1696         btsnd_hcic_rem_oob_reply (bd_addr, c, r);
1697     }
1698 }
1699
1700 /*******************************************************************************
1701 **
1702 ** Function         BTM_BuildOobData
1703 **
1704 ** Description      This function is called to build the OOB data payload to
1705 **                  be sent over OOB (non-Bluetooth) link
1706 **
1707 ** Parameters:      p_data  - the location for OOB data
1708 **                  max_len - p_data size.
1709 **                  c       - simple pairing Hash C.
1710 **                  r       - simple pairing Randomizer  C.
1711 **                  name_len- 0, local device name would not be included.
1712 **                            otherwise, the local device name is included for
1713 **                            up to this specified length
1714 **
1715 ** Returns          Number of bytes in p_data.
1716 **
1717 *******************************************************************************/
1718 UINT16 BTM_BuildOobData(UINT8 *p_data, UINT16 max_len, BT_OCTET16 c,
1719                         BT_OCTET16 r, UINT8 name_len)
1720 {
1721     UINT8   *p = p_data;
1722     UINT16  len = 0;
1723 #if BTM_MAX_LOC_BD_NAME_LEN > 0
1724     UINT16  name_size;
1725     UINT8   name_type = BTM_EIR_SHORTENED_LOCAL_NAME_TYPE;
1726 #endif
1727
1728     if (p_data && max_len >= BTM_OOB_MANDATORY_SIZE)
1729     {
1730         /* add mandatory part */
1731         UINT16_TO_STREAM(p, len);
1732         BDADDR_TO_STREAM(p, controller_get_interface()->get_address()->address);
1733
1734         len = BTM_OOB_MANDATORY_SIZE;
1735         max_len -= len;
1736
1737         /* now optional part */
1738
1739         /* add Hash C */
1740         UINT16 delta = BTM_OOB_HASH_C_SIZE + 2;
1741         if (max_len >= delta)
1742         {
1743             *p++ = BTM_OOB_HASH_C_SIZE + 1;
1744             *p++ = BTM_EIR_OOB_SSP_HASH_C_TYPE;
1745             ARRAY_TO_STREAM(p, c, BTM_OOB_HASH_C_SIZE);
1746             len     += delta;
1747             max_len -= delta;
1748         }
1749
1750         /* add Rand R */
1751         delta = BTM_OOB_RAND_R_SIZE + 2;
1752         if (max_len >= delta)
1753         {
1754             *p++ = BTM_OOB_RAND_R_SIZE + 1;
1755             *p++ = BTM_EIR_OOB_SSP_RAND_R_TYPE;
1756             ARRAY_TO_STREAM(p, r, BTM_OOB_RAND_R_SIZE);
1757             len     += delta;
1758             max_len -= delta;
1759         }
1760
1761         /* add class of device */
1762         delta = BTM_OOB_COD_SIZE + 2;
1763         if (max_len >= delta)
1764         {
1765             *p++ = BTM_OOB_COD_SIZE + 1;
1766             *p++ = BTM_EIR_OOB_COD_TYPE;
1767             DEVCLASS_TO_STREAM(p, btm_cb.devcb.dev_class);
1768             len     += delta;
1769             max_len -= delta;
1770         }
1771 #if BTM_MAX_LOC_BD_NAME_LEN > 0
1772         name_size = name_len;
1773         if (name_size > strlen(btm_cb.cfg.bd_name))
1774         {
1775             name_type = BTM_EIR_COMPLETE_LOCAL_NAME_TYPE;
1776             name_size = (UINT16)strlen(btm_cb.cfg.bd_name);
1777         }
1778         delta = name_size + 2;
1779         if (max_len >= delta)
1780         {
1781             *p++ = name_size + 1;
1782             *p++ = name_type;
1783             ARRAY_TO_STREAM (p, btm_cb.cfg.bd_name, name_size);
1784             len     += delta;
1785             max_len -= delta;
1786         }
1787 #endif
1788         /* update len */
1789         p = p_data;
1790         UINT16_TO_STREAM(p, len);
1791     }
1792     return len;
1793 }
1794
1795 /*******************************************************************************
1796 **
1797 ** Function         BTM_BothEndsSupportSecureConnections
1798 **
1799 ** Description      This function is called to check if both the local device and the peer device
1800 **                  specified by bd_addr support BR/EDR Secure Connections.
1801 **
1802 ** Parameters:      bd_addr - address of the peer
1803 **
1804 ** Returns          TRUE if BR/EDR Secure Connections are supported by both local
1805 **                  and the remote device.
1806 **                  else FALSE.
1807 **
1808 *******************************************************************************/
1809 BOOLEAN BTM_BothEndsSupportSecureConnections(BD_ADDR bd_addr)
1810 {
1811     return ((controller_get_interface()->supports_secure_connections()) &&
1812             (BTM_PeerSupportsSecureConnections(bd_addr)));
1813 }
1814
1815 /*******************************************************************************
1816 **
1817 ** Function         BTM_PeerSupportsSecureConnections
1818 **
1819 ** Description      This function is called to check if the peer supports
1820 **                  BR/EDR Secure Connections.
1821 **
1822 ** Parameters:      bd_addr - address of the peer
1823 **
1824 ** Returns          TRUE if BR/EDR Secure Connections are supported by the peer,
1825 **                  else FALSE.
1826 **
1827 *******************************************************************************/
1828 BOOLEAN BTM_PeerSupportsSecureConnections(BD_ADDR bd_addr)
1829 {
1830     tBTM_SEC_DEV_REC    *p_dev_rec;
1831
1832     if ((p_dev_rec = btm_find_dev(bd_addr)) == NULL)
1833     {
1834         BTM_TRACE_WARNING("%s: unknown BDA: %08x%04x", __FUNCTION__,
1835             (bd_addr[0]<<24) + (bd_addr[1]<<16) + (bd_addr[2]<<8) + bd_addr[3],
1836             (bd_addr[4]<< 8) + bd_addr[5]);
1837         return FALSE;
1838     }
1839
1840     return (p_dev_rec->remote_supports_secure_connections);
1841 }
1842
1843 /*******************************************************************************
1844 **
1845 ** Function         BTM_ReadOobData
1846 **
1847 ** Description      This function is called to parse the OOB data payload
1848 **                  received over OOB (non-Bluetooth) link
1849 **
1850 ** Parameters:      p_data  - the location for OOB data
1851 **                  eir_tag - The associated EIR tag to read the data.
1852 **                  *p_len(output) - the length of the data with the given tag.
1853 **
1854 ** Returns          the beginning of the data with the given tag.
1855 **                  NULL, if the tag is not found.
1856 **
1857 *******************************************************************************/
1858 UINT8 * BTM_ReadOobData(UINT8 *p_data, UINT8 eir_tag, UINT8 *p_len)
1859 {
1860     UINT8   *p = p_data;
1861     UINT16  max_len;
1862     UINT8   len, type;
1863     UINT8   *p_ret = NULL;
1864     UINT8   ret_len = 0;
1865
1866     if (p_data)
1867     {
1868         STREAM_TO_UINT16(max_len, p);
1869         if (max_len >= BTM_OOB_MANDATORY_SIZE)
1870         {
1871             if (BTM_EIR_OOB_BD_ADDR_TYPE == eir_tag)
1872             {
1873                 p_ret = p; /* the location for bd_addr */
1874                 ret_len = BTM_OOB_BD_ADDR_SIZE;
1875             }
1876             else
1877             {
1878                 p += BD_ADDR_LEN;
1879                 max_len -= BTM_OOB_MANDATORY_SIZE;
1880                 /* now the optional data in EIR format */
1881                 while (max_len > 0)
1882                 {
1883                     len     = *p++; /* tag data len + 1 */
1884                     type    = *p++;
1885                     if (eir_tag == type)
1886                     {
1887                         p_ret = p;
1888                         ret_len = len - 1;
1889                         break;
1890                     }
1891                     /* the data size of this tag is len + 1 (tag data len + 2) */
1892                     if (max_len > len)
1893                     {
1894                         max_len -= len;
1895                         max_len--;
1896                         len--;
1897                         p += len;
1898                     }
1899                     else
1900                         max_len = 0;
1901                 }
1902             }
1903         }
1904     }
1905
1906     if (p_len)
1907         *p_len = ret_len;
1908
1909     return p_ret;
1910 }
1911 #endif
1912
1913 /*******************************************************************************
1914 **
1915 ** Function         BTM_SetOutService
1916 **
1917 ** Description      This function is called to set the service for
1918 **                  outgoing connections.
1919 **
1920 **                  If the profile/application calls BTM_SetSecurityLevel
1921 **                  before initiating a connection, this function does not
1922 **                  need to be called.
1923 **
1924 ** Returns          void
1925 **
1926 *******************************************************************************/
1927 void BTM_SetOutService(BD_ADDR bd_addr, UINT8 service_id, UINT32 mx_chan_id)
1928 {
1929     tBTM_SEC_DEV_REC *p_dev_rec;
1930     tBTM_SEC_SERV_REC *p_serv_rec = &btm_cb.sec_serv_rec[0];
1931
1932     btm_cb.p_out_serv = p_serv_rec;
1933     p_dev_rec = btm_find_dev (bd_addr);
1934
1935     for (int i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++)
1936     {
1937         if ((p_serv_rec->security_flags & BTM_SEC_IN_USE)
1938             && (p_serv_rec->service_id == service_id)
1939             && (p_serv_rec->orig_mx_chan_id == mx_chan_id))
1940         {
1941             BTM_TRACE_API("BTM_SetOutService p_out_serv id %d, psm 0x%04x, proto_id %d, chan_id %d",
1942                            p_serv_rec->service_id, p_serv_rec->psm, p_serv_rec->mx_proto_id, p_serv_rec->orig_mx_chan_id);
1943             btm_cb.p_out_serv = p_serv_rec;
1944             if (p_dev_rec)
1945                 p_dev_rec->p_cur_service = p_serv_rec;
1946             break;
1947         }
1948     }
1949 }
1950
1951 /************************************************************************
1952 **              I N T E R N A L     F U N C T I O N S
1953 *************************************************************************/
1954 /*******************************************************************************
1955 **
1956 ** Function         btm_sec_is_upgrade_possible
1957 **
1958 ** Description      This function returns TRUE if the existing link key
1959 **                  can be upgraded or if the link key does not exist.
1960 **
1961 ** Returns          BOOLEAN
1962 **
1963 *******************************************************************************/
1964 static BOOLEAN btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC  *p_dev_rec, BOOLEAN is_originator)
1965 {
1966     UINT16              mtm_check = is_originator ? BTM_SEC_OUT_MITM : BTM_SEC_IN_MITM;
1967     BOOLEAN             is_possible = TRUE;
1968
1969     if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)
1970     {
1971         is_possible = FALSE;
1972         if(p_dev_rec->p_cur_service)
1973         {
1974             BTM_TRACE_DEBUG ("%s() id: %d, link_key_typet: %d, rmt_io_caps: %d, chk flags: 0x%x, flags: 0x%x",
1975                           __func__, p_dev_rec->p_cur_service->service_id, p_dev_rec->link_key_type,
1976                           p_dev_rec->rmt_io_caps, mtm_check, p_dev_rec->p_cur_service->security_flags);
1977         }
1978         else
1979         {
1980             BTM_TRACE_DEBUG ("%s() link_key_typet: %d, rmt_io_caps: %d, chk flags: 0x%x",
1981                           __func__, p_dev_rec->link_key_type, p_dev_rec->rmt_io_caps, mtm_check);
1982         }
1983         /* Already have a link key to the connected peer. Is the link key secure enough?
1984         ** Is a link key upgrade even possible?
1985         */
1986         if ((p_dev_rec->security_required & mtm_check)    /* needs MITM */
1987             && ((p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB) ||
1988                 (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256))
1989                                                           /* has unauthenticated
1990                                                           link key */
1991             && (p_dev_rec->rmt_io_caps < BTM_IO_CAP_MAX)  /* a valid peer IO cap */
1992             && (btm_sec_io_map[p_dev_rec->rmt_io_caps][btm_cb.devcb.loc_io_caps]))
1993                                                           /* authenticated
1994                                                           link key is possible */
1995         {
1996             /* upgrade is possible: check if the application wants the upgrade.
1997              * If the application is configured to use a global MITM flag,
1998              * it probably would not want to upgrade the link key based on the security level database */
1999             is_possible = TRUE;
2000         }
2001     }
2002     BTM_TRACE_DEBUG ("%s() is_possible: %d sec_flags: 0x%x", __func__, is_possible, p_dev_rec->sec_flags);
2003     return is_possible;
2004 }
2005
2006 /*******************************************************************************
2007 **
2008 ** Function         btm_sec_check_upgrade
2009 **
2010 ** Description      This function is called to check if the existing link key
2011 **                  needs to be upgraded.
2012 **
2013 ** Returns          void
2014 **
2015 *******************************************************************************/
2016 static void btm_sec_check_upgrade(tBTM_SEC_DEV_REC  *p_dev_rec, BOOLEAN is_originator)
2017 {
2018
2019     BTM_TRACE_DEBUG ("%s()", __func__);
2020
2021     /* Only check if link key already exists */
2022     if (!(p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN))
2023         return;
2024
2025     if (btm_sec_is_upgrade_possible (p_dev_rec, is_originator) == TRUE)
2026     {
2027         BTM_TRACE_DEBUG ("need upgrade!! sec_flags:0x%x", p_dev_rec->sec_flags);
2028         /* upgrade is possible: check if the application wants the upgrade.
2029          * If the application is configured to use a global MITM flag,
2030          * it probably would not want to upgrade the link key based on the security level database */
2031         tBTM_SP_UPGRADE evt_data;
2032         memcpy (evt_data.bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN);
2033         evt_data.upgrade = TRUE;
2034         if (btm_cb.api.p_sp_callback)
2035             (*btm_cb.api.p_sp_callback) (BTM_SP_UPGRADE_EVT, (tBTM_SP_EVT_DATA *)&evt_data);
2036
2037         BTM_TRACE_DEBUG ("evt_data.upgrade:0x%x", evt_data.upgrade);
2038         if (evt_data.upgrade)
2039         {
2040             /* if the application confirms the upgrade, set the upgrade bit */
2041             p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
2042
2043             /* Clear the link key known to go through authentication/pairing again */
2044             p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED);
2045             p_dev_rec->sec_flags &= ~BTM_SEC_AUTHENTICATED;
2046             BTM_TRACE_DEBUG ("sec_flags:0x%x", p_dev_rec->sec_flags);
2047         }
2048     }
2049 }
2050
2051 /*******************************************************************************
2052 **
2053 ** Function         btm_sec_l2cap_access_req
2054 **
2055 ** Description      This function is called by the L2CAP to grant permission to
2056 **                  establish L2CAP connection to or from the peer device.
2057 **
2058 ** Parameters:      bd_addr       - Address of the peer device
2059 **                  psm           - L2CAP PSM
2060 **                  is_originator - TRUE if protocol above L2CAP originates
2061 **                                  connection
2062 **                  p_callback    - Pointer to callback function called if
2063 **                                  this function returns PENDING after required
2064 **                                  procedures are complete. MUST NOT BE NULL.
2065 **
2066 ** Returns          tBTM_STATUS
2067 **
2068 *******************************************************************************/
2069 #define BTM_SEC_OUT_FLAGS   (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHORIZE)
2070 #define BTM_SEC_IN_FLAGS    (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHORIZE)
2071
2072 #define BTM_SEC_OUT_LEVEL4_FLAGS   (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT | \
2073                                     BTM_SEC_OUT_MITM | BTM_SEC_MODE4_LEVEL4)
2074
2075 #define BTM_SEC_IN_LEVEL4_FLAGS    (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | \
2076                                     BTM_SEC_IN_MITM | BTM_SEC_MODE4_LEVEL4)
2077
2078 tBTM_STATUS btm_sec_l2cap_access_req (BD_ADDR bd_addr, UINT16 psm, UINT16 handle,
2079                                       CONNECTION_TYPE conn_type,
2080                                       tBTM_SEC_CALLBACK *p_callback,
2081                                       void *p_ref_data)
2082 {
2083     tBTM_SEC_DEV_REC  *p_dev_rec;
2084     tBTM_SEC_SERV_REC *p_serv_rec;
2085     UINT16         security_required;
2086     UINT16         old_security_required;
2087     BOOLEAN       old_is_originator;
2088     tBTM_STATUS   rc = BTM_SUCCESS;
2089     BOOLEAN       chk_acp_auth_done = FALSE;
2090     BOOLEAN is_originator;
2091     BOOLEAN     transport = FALSE; /* should check PSM range in LE connection oriented L2CAP connection */
2092
2093 #if (L2CAP_UCD_INCLUDED == TRUE)
2094     if (conn_type & CONNECTION_TYPE_ORIG_MASK)
2095         is_originator = TRUE;
2096     else
2097         is_originator = FALSE;
2098
2099     BTM_TRACE_DEBUG ("%s() conn_type: 0x%x, 0x%x", __func__, conn_type, p_ref_data);
2100 #else
2101     is_originator = conn_type;
2102
2103     BTM_TRACE_DEBUG ("%s() is_originator:%d, 0x%x", __func__, is_originator, p_ref_data);
2104 #endif
2105
2106     /* Find or get oldest record */
2107     p_dev_rec = btm_find_or_alloc_dev (bd_addr);
2108
2109     p_dev_rec->hci_handle = handle;
2110
2111     /* Find the service record for the PSM */
2112     p_serv_rec = btm_sec_find_first_serv (conn_type, psm);
2113
2114     /* If there is no application registered with this PSM do not allow connection */
2115     if (!p_serv_rec)
2116     {
2117         BTM_TRACE_WARNING ("%s() PSM: %d no application registerd", __func__, psm);
2118         (*p_callback) (bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED);
2119         return(BTM_MODE_UNSUPPORTED);
2120     }
2121
2122     /* Services level0 by default have no security */
2123     if ((btm_sec_is_serv_level0(psm)) && (!btm_cb.devcb.secure_connections_only))
2124     {
2125         (*p_callback) (bd_addr,transport, p_ref_data, BTM_SUCCESS_NO_SECURITY);
2126         return(BTM_SUCCESS);
2127     }
2128 #if (L2CAP_UCD_INCLUDED == TRUE)
2129     if ( conn_type & CONNECTION_TYPE_CONNLESS_MASK )
2130     {
2131         if (btm_cb.security_mode == BTM_SEC_MODE_SC)
2132         {
2133             security_required = btm_sec_set_serv_level4_flags (p_serv_rec->ucd_security_flags,
2134                                                                is_originator);
2135         }
2136         else
2137         {
2138             security_required = p_serv_rec->ucd_security_flags;
2139         }
2140
2141         rc = BTM_CMD_STARTED;
2142         if (is_originator)
2143         {
2144             if (((security_required & BTM_SEC_OUT_FLAGS) == 0) ||
2145                 ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_AUTHENTICATE) && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))) ||
2146                 ((((security_required & BTM_SEC_OUT_FLAGS) == (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED))) ||
2147                 ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_FLAGS) && (p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED))) )
2148             {
2149                 rc = BTM_SUCCESS;
2150             }
2151         }
2152         else
2153         {
2154             if (((security_required & BTM_SEC_IN_FLAGS) == 0) ||
2155                 ((((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHENTICATE) && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))) ||
2156                 ((((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED))) ||
2157                 ((((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_FLAGS) && (p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED))) )
2158             {
2159                 rc = BTM_SUCCESS;
2160             }
2161         }
2162
2163         if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) &&
2164             (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
2165         {
2166             rc = BTM_CMD_STARTED;
2167         }
2168
2169         if (rc == BTM_SUCCESS)
2170         {
2171             if (p_callback)
2172                 (*p_callback) (bd_addr, transport, (void *)p_ref_data, BTM_SUCCESS);
2173
2174             return(BTM_SUCCESS);
2175         }
2176     }
2177     else
2178 #endif
2179     {
2180         if (btm_cb.security_mode == BTM_SEC_MODE_SC)
2181         {
2182             security_required = btm_sec_set_serv_level4_flags (p_serv_rec->security_flags,
2183                                                                 is_originator);
2184         }
2185         else
2186         {
2187             security_required = p_serv_rec->security_flags;
2188         }
2189     }
2190
2191     BTM_TRACE_DEBUG("%s: security_required 0x%04x, is_originator 0x%02x, psm  0x%04x",
2192                     __FUNCTION__, security_required, is_originator, psm);
2193
2194     if ((!is_originator) && (security_required & BTM_SEC_MODE4_LEVEL4))
2195     {
2196         BOOLEAN local_supports_sc = controller_get_interface()->supports_secure_connections();
2197         /* acceptor receives L2CAP Channel Connect Request for Secure Connections Only service */
2198         if (!(local_supports_sc) || !(p_dev_rec->remote_supports_secure_connections))
2199         {
2200             BTM_TRACE_DEBUG("%s: SC only service, local_support_for_sc %d",
2201                             "rmt_support_for_sc : %d -> fail pairing", __FUNCTION__,
2202                             local_supports_sc,
2203                             p_dev_rec->remote_supports_secure_connections);
2204             if (p_callback)
2205                 (*p_callback) (bd_addr, transport, (void *)p_ref_data,
2206                                                     BTM_MODE4_LEVEL4_NOT_SUPPORTED);
2207
2208             return (BTM_MODE4_LEVEL4_NOT_SUPPORTED);
2209         }
2210     }
2211
2212     /* there are some devices (moto KRZR) which connects to several services at the same time */
2213     /* we will process one after another */
2214     if ( (p_dev_rec->p_callback) || (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) )
2215     {
2216         BTM_TRACE_EVENT ("%s() - busy - PSM:%d delayed  state: %s mode:%d, sm4:0x%x", __func__,
2217                           psm, btm_pair_state_descr(btm_cb.pairing_state), btm_cb.security_mode, p_dev_rec->sm4);
2218         BTM_TRACE_EVENT ("security_flags:x%x, sec_flags:x%x", security_required, p_dev_rec->sec_flags);
2219         rc = BTM_CMD_STARTED;
2220         if ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED ||
2221              btm_cb.security_mode == BTM_SEC_MODE_NONE ||
2222              btm_cb.security_mode == BTM_SEC_MODE_SERVICE ||
2223              btm_cb.security_mode == BTM_SEC_MODE_LINK) ||
2224             (BTM_SM4_KNOWN == p_dev_rec->sm4) || (BTM_SEC_IS_SM4(p_dev_rec->sm4) &&
2225             (btm_sec_is_upgrade_possible(p_dev_rec, is_originator) == FALSE)))
2226         {
2227             /* legacy mode - local is legacy or local is lisbon/peer is legacy
2228              * or SM4 with no possibility of link key upgrade */
2229             if (is_originator)
2230             {
2231                 if (((security_required & BTM_SEC_OUT_FLAGS) == 0) ||
2232                     ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec))) ||
2233                     ((((security_required & BTM_SEC_OUT_FLAGS) == (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && btm_dev_encrypted(p_dev_rec))) ||
2234                     ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_FLAGS) && btm_dev_authorized(p_dev_rec)  && btm_dev_encrypted(p_dev_rec))) )
2235                 {
2236                     rc = BTM_SUCCESS;
2237                 }
2238             }
2239             else
2240             {
2241                 if (((security_required & BTM_SEC_IN_FLAGS) == 0) ||
2242                 (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec)) ||
2243                 (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && btm_dev_encrypted(p_dev_rec)) ||
2244                 (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHORIZE) && (btm_dev_authorized(p_dev_rec)||btm_serv_trusted(p_dev_rec, p_serv_rec))) ||
2245                 (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_AUTHORIZE)) && ((btm_dev_authorized(p_dev_rec)||btm_serv_trusted(p_dev_rec, p_serv_rec)) && btm_dev_authenticated(p_dev_rec))) ||
2246                 (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHORIZE)) && ((btm_dev_authorized(p_dev_rec)||btm_serv_trusted(p_dev_rec, p_serv_rec)) && btm_dev_encrypted(p_dev_rec))) ||
2247                 (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_FLAGS)  && btm_dev_encrypted(p_dev_rec) && (btm_dev_authorized(p_dev_rec)||btm_serv_trusted(p_dev_rec, p_serv_rec))))
2248                 {
2249                     rc = BTM_SUCCESS;
2250                 }
2251             }
2252
2253             if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) &&
2254                 (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
2255             {
2256                 rc = BTM_CMD_STARTED;
2257             }
2258
2259             if (rc == BTM_SUCCESS)
2260             {
2261                 if (p_callback)
2262                     (*p_callback) (bd_addr, transport, (void *)p_ref_data, BTM_SUCCESS);
2263                 return(BTM_SUCCESS);
2264             }
2265         }
2266
2267         btm_cb.sec_req_pending = TRUE;
2268         return(BTM_CMD_STARTED);
2269     }
2270
2271     /* Save pointer to service record */
2272     p_dev_rec->p_cur_service = p_serv_rec;
2273
2274     /* Modify security_required in btm_sec_l2cap_access_req for Lisbon */
2275     if (btm_cb.security_mode == BTM_SEC_MODE_SP ||
2276         btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
2277         btm_cb.security_mode == BTM_SEC_MODE_SC)
2278     {
2279         if (BTM_SEC_IS_SM4(p_dev_rec->sm4))
2280         {
2281             if (is_originator)
2282             {
2283                 /* SM4 to SM4 -> always authenticate & encrypt */
2284                 security_required |= (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT);
2285             }
2286             else /* acceptor */
2287             {
2288                 /* SM4 to SM4: the acceptor needs to make sure the authentication is already done */
2289                 chk_acp_auth_done = TRUE;
2290                 /* SM4 to SM4 -> always authenticate & encrypt */
2291                 security_required |= (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT);
2292            }
2293         }
2294         else if (!(BTM_SM4_KNOWN & p_dev_rec->sm4))
2295         {
2296             /* the remote features are not known yet */
2297             BTM_TRACE_DEBUG("%s: (%s) remote features unknown!!sec_flags:0x%02x", __FUNCTION__,
2298                             (is_originator) ? "initiator" : "acceptor", p_dev_rec->sec_flags);
2299
2300             p_dev_rec->sm4 |= BTM_SM4_REQ_PEND;
2301             return (BTM_CMD_STARTED);
2302         }
2303     }
2304
2305     BTM_TRACE_DEBUG ("%s()  sm4:0x%x, sec_flags:0x%x, security_required:0x%x chk:%d", __func__,
2306                       p_dev_rec->sm4, p_dev_rec->sec_flags, security_required, chk_acp_auth_done);
2307
2308     old_security_required        = p_dev_rec->security_required;
2309     old_is_originator            = p_dev_rec->is_originator;
2310     p_dev_rec->security_required = security_required;
2311     p_dev_rec->p_ref_data        = p_ref_data;
2312     p_dev_rec->is_originator     = is_originator;
2313
2314 #if (L2CAP_UCD_INCLUDED == TRUE)
2315     if ( conn_type & CONNECTION_TYPE_CONNLESS_MASK )
2316         p_dev_rec->is_ucd = TRUE;
2317     else
2318         p_dev_rec->is_ucd = FALSE;
2319 #endif
2320
2321     /* If there are multiple service records used through the same PSM */
2322     /* leave security decision for the multiplexor on the top */
2323 #if (L2CAP_UCD_INCLUDED == TRUE)
2324     if (((btm_sec_find_next_serv (p_serv_rec)) != NULL)
2325         &&(!( conn_type & CONNECTION_TYPE_CONNLESS_MASK ))) /* if not UCD */
2326 #else
2327     if ((btm_sec_find_next_serv (p_serv_rec)) != NULL)
2328 #endif
2329     {
2330         BTM_TRACE_DEBUG ("no next_serv sm4:0x%x, chk:%d", p_dev_rec->sm4, chk_acp_auth_done);
2331         if (!BTM_SEC_IS_SM4(p_dev_rec->sm4))
2332         {
2333             BTM_TRACE_EVENT ("Security Manager: l2cap_access_req PSM:%d postponed for multiplexer", psm);
2334             /* pre-Lisbon: restore the old settings */
2335             p_dev_rec->security_required = old_security_required;
2336             p_dev_rec->is_originator     = old_is_originator;
2337
2338             (*p_callback) (bd_addr, transport, p_ref_data, BTM_SUCCESS);
2339
2340             return(BTM_SUCCESS);
2341         }
2342     }
2343
2344     /* if the originator is using dynamic PSM in legacy mode, do not start any security process now
2345      * The layer above L2CAP needs to carry out the security requirement after L2CAP connect
2346      * response is received */
2347     if (is_originator &&
2348         ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED ||
2349           btm_cb.security_mode == BTM_SEC_MODE_NONE ||
2350           btm_cb.security_mode == BTM_SEC_MODE_SERVICE ||
2351           btm_cb.security_mode == BTM_SEC_MODE_LINK) ||
2352          !BTM_SEC_IS_SM4(p_dev_rec->sm4)) && (psm >= 0x1001))
2353     {
2354         BTM_TRACE_EVENT ("dynamic PSM:0x%x in legacy mode - postponed for upper layer", psm);
2355         /* restore the old settings */
2356         p_dev_rec->security_required = old_security_required;
2357         p_dev_rec->is_originator     = old_is_originator;
2358
2359         (*p_callback) (bd_addr, transport, p_ref_data, BTM_SUCCESS);
2360
2361         return(BTM_SUCCESS);
2362     }
2363
2364     if (chk_acp_auth_done)
2365     {
2366         BTM_TRACE_DEBUG ("(SM4 to SM4) btm_sec_l2cap_access_req rspd. authenticated: x%x, enc: x%x",
2367                           (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED), (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED));
2368         /* SM4, but we do not know for sure which level of security we need.
2369          * as long as we have a link key, it's OK */
2370         if ((0 == (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))
2371             ||(0 == (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED)))
2372         {
2373             rc = BTM_DELAY_CHECK;
2374             /*
2375             2046 may report HCI_Encryption_Change and L2C Connection Request out of sequence
2376             because of data path issues. Delay this disconnect a little bit
2377             */
2378             LOG_INFO("%s peer should have initiated security process by now (SM4 to SM4)", __func__);
2379             p_dev_rec->p_callback        = p_callback;
2380             p_dev_rec->sec_state         = BTM_SEC_STATE_DELAY_FOR_ENC;
2381             (*p_callback) (bd_addr, transport, p_ref_data, rc);
2382
2383             return BTM_SUCCESS;
2384         }
2385     }
2386
2387     p_dev_rec->p_callback        = p_callback;
2388
2389     if (p_dev_rec->last_author_service_id == BTM_SEC_NO_LAST_SERVICE_ID
2390         || p_dev_rec->last_author_service_id != p_dev_rec->p_cur_service->service_id)
2391     {
2392         /* Although authentication and encryption are per connection
2393         ** authorization is per access request.  For example when serial connection
2394         ** is up and authorized and client requests to read file (access to other
2395         ** scn), we need to request user's permission again.
2396         */
2397         p_dev_rec->sec_flags &= ~BTM_SEC_AUTHORIZED;
2398     }
2399
2400     if (BTM_SEC_IS_SM4(p_dev_rec->sm4))
2401     {
2402         if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) &&
2403             (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
2404         {
2405             /* BTM_LKEY_TYPE_AUTH_COMB_P_256 is the only acceptable key in this case */
2406             if ((p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) != 0)
2407             {
2408                 p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
2409             }
2410             p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
2411                                       BTM_SEC_AUTHENTICATED);
2412             BTM_TRACE_DEBUG ("%s: sec_flags:0x%x", __FUNCTION__, p_dev_rec->sec_flags);
2413         }
2414         else
2415         {
2416             /* If we already have a link key to the connected peer, is it secure enough? */
2417             btm_sec_check_upgrade(p_dev_rec, is_originator);
2418         }
2419     }
2420
2421     BTM_TRACE_EVENT ("%s() PSM:%d Handle:%d State:%d Flags: 0x%x Required: 0x%x Service ID:%d",
2422            __func__, psm, handle, p_dev_rec->sec_state, p_dev_rec->sec_flags,
2423            p_dev_rec->security_required, p_dev_rec->p_cur_service->service_id);
2424
2425     if ((rc = btm_sec_execute_procedure (p_dev_rec)) != BTM_CMD_STARTED)
2426     {
2427         p_dev_rec->p_callback = NULL;
2428         (*p_callback) (bd_addr, transport, p_dev_rec->p_ref_data, (UINT8)rc);
2429     }
2430
2431     return(rc);
2432 }
2433
2434 /*******************************************************************************
2435 **
2436 ** Function         btm_sec_mx_access_request
2437 **
2438 ** Description      This function is called by all Multiplexing Protocols during
2439 **                  establishing connection to or from peer device to grant
2440 **                  permission to establish application connection.
2441 **
2442 ** Parameters:      bd_addr       - Address of the peer device
2443 **                  psm           - L2CAP PSM
2444 **                  is_originator - TRUE if protocol above L2CAP originates
2445 **                                  connection
2446 **                  mx_proto_id   - protocol ID of the multiplexer
2447 **                  mx_chan_id    - multiplexer channel to reach application
2448 **                  p_callback    - Pointer to callback function called if
2449 **                                  this function returns PENDING after required
2450 **                                  procedures are completed
2451 **                  p_ref_data    - Pointer to any reference data needed by the
2452 **                                  the callback function.
2453 **
2454 ** Returns          BTM_CMD_STARTED
2455 **
2456 *******************************************************************************/
2457 tBTM_STATUS btm_sec_mx_access_request (BD_ADDR bd_addr, UINT16 psm, BOOLEAN is_originator,
2458                                        UINT32 mx_proto_id, UINT32 mx_chan_id,
2459                                        tBTM_SEC_CALLBACK *p_callback, void *p_ref_data)
2460 {
2461     tBTM_SEC_DEV_REC  *p_dev_rec;
2462     tBTM_SEC_SERV_REC *p_serv_rec;
2463     tBTM_STATUS        rc;
2464     UINT16             security_required;
2465     BOOLEAN transport   = FALSE;/* should check PSM range in LE connection oriented L2CAP connection */
2466
2467     BTM_TRACE_DEBUG ("%s() is_originator: %d", __func__, is_originator);
2468     /* Find or get oldest record */
2469     p_dev_rec = btm_find_or_alloc_dev (bd_addr);
2470
2471     /* Find the service record for the PSM */
2472     p_serv_rec = btm_sec_find_mx_serv (is_originator, psm, mx_proto_id, mx_chan_id);
2473
2474     /* If there is no application registered with this PSM do not allow connection */
2475     if (!p_serv_rec)
2476     {
2477         if (p_callback)
2478             (*p_callback) (bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED);
2479
2480         BTM_TRACE_ERROR ("Security Manager: MX service not found PSM:%d Proto:%d SCN:%d",
2481                           psm, mx_proto_id, mx_chan_id);
2482         return BTM_NO_RESOURCES;
2483     }
2484
2485     if ((btm_cb.security_mode == BTM_SEC_MODE_SC) && (!btm_sec_is_serv_level0(psm)))
2486     {
2487         security_required = btm_sec_set_serv_level4_flags (p_serv_rec->security_flags,
2488                                                            is_originator);
2489     }
2490     else
2491     {
2492         security_required = p_serv_rec->security_flags;
2493     }
2494
2495     /* there are some devices (moto phone) which connects to several services at the same time */
2496     /* we will process one after another */
2497     if ( (p_dev_rec->p_callback) || (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) )
2498     {
2499         BTM_TRACE_EVENT ("%s() service PSM:%d Proto:%d SCN:%d delayed  state: %s", __func__,
2500                           psm, mx_proto_id, mx_chan_id, btm_pair_state_descr(btm_cb.pairing_state));
2501
2502         rc = BTM_CMD_STARTED;
2503
2504         if ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED ||
2505              btm_cb.security_mode == BTM_SEC_MODE_NONE ||
2506              btm_cb.security_mode == BTM_SEC_MODE_SERVICE ||
2507              btm_cb.security_mode == BTM_SEC_MODE_LINK) ||
2508             (BTM_SM4_KNOWN == p_dev_rec->sm4) || (BTM_SEC_IS_SM4(p_dev_rec->sm4) &&
2509             (btm_sec_is_upgrade_possible(p_dev_rec, is_originator) == FALSE)))
2510         {
2511             /* legacy mode - local is legacy or local is lisbon/peer is legacy
2512              * or SM4 with no possibility of link key upgrade */
2513             if (is_originator)
2514             {
2515                 if (((security_required & BTM_SEC_OUT_FLAGS) == 0) ||
2516                     ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec))) ||
2517                     ((((security_required & BTM_SEC_OUT_FLAGS) == (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && btm_dev_encrypted(p_dev_rec)))
2518                     )
2519                 {
2520                     rc = BTM_SUCCESS;
2521                 }
2522             }
2523             else
2524             {
2525                 if (((security_required & BTM_SEC_IN_FLAGS) == 0) ||
2526                     ((((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec))) ||
2527                     (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHORIZE) && (btm_dev_authorized(p_dev_rec)||btm_serv_trusted(p_dev_rec, p_serv_rec))) ||
2528                     (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_AUTHENTICATE)) && ((btm_dev_authorized(p_dev_rec)||btm_serv_trusted(p_dev_rec, p_serv_rec)) && btm_dev_authenticated(p_dev_rec))) ||
2529                     (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT)) && ((btm_dev_authorized(p_dev_rec)||btm_serv_trusted(p_dev_rec, p_serv_rec))&& btm_dev_encrypted(p_dev_rec))) ||
2530                     ((((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && btm_dev_encrypted(p_dev_rec)))
2531                     )
2532                 {
2533                     rc = BTM_SUCCESS;
2534                 }
2535             }
2536             if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) &&
2537                 (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
2538             {
2539                 rc = BTM_CMD_STARTED;
2540             }
2541         }
2542
2543         if (rc == BTM_SUCCESS)
2544         {
2545             BTM_TRACE_EVENT("%s: allow to bypass, checking authorization", __FUNCTION__);
2546             /* the security in BTM_SEC_IN_FLAGS is fullfilled so far, check the requirements in */
2547             /* btm_sec_execute_procedure */
2548             if ((is_originator && (p_serv_rec->security_flags & BTM_SEC_OUT_AUTHORIZE)) ||
2549                 (!is_originator && (p_serv_rec->security_flags & BTM_SEC_IN_AUTHORIZE)))
2550             {
2551                 BTM_TRACE_EVENT("%s: still need authorization", __FUNCTION__);
2552                 rc = BTM_CMD_STARTED;
2553             }
2554         }
2555
2556         /* Check whether there is a pending security procedure, if so we should always queue */
2557         /* the new security request */
2558         if (p_dev_rec->sec_state != BTM_SEC_STATE_IDLE)
2559         {
2560             BTM_TRACE_EVENT("%s: There is a pending security procedure", __FUNCTION__);
2561             rc = BTM_CMD_STARTED;
2562         }
2563         if (rc == BTM_CMD_STARTED)
2564         {
2565             BTM_TRACE_EVENT("%s: call btm_sec_queue_mx_request", __FUNCTION__);
2566             btm_sec_queue_mx_request (bd_addr, psm,  is_originator, mx_proto_id,
2567                                       mx_chan_id, p_callback, p_ref_data);
2568         }
2569         else /* rc == BTM_SUCCESS */
2570         {
2571             /* access granted */
2572              if (p_callback)
2573             {
2574                 (*p_callback) (bd_addr, transport, p_ref_data, (UINT8)rc);
2575             }
2576         }
2577
2578         BTM_TRACE_EVENT("%s: return with rc = 0x%02x in delayed state %s", __FUNCTION__, rc,
2579                           btm_pair_state_descr(btm_cb.pairing_state));
2580         return rc;
2581     }
2582
2583     if ((!is_originator) && ((security_required & BTM_SEC_MODE4_LEVEL4) ||
2584         (btm_cb.security_mode == BTM_SEC_MODE_SC)))
2585     {
2586         BOOLEAN local_supports_sc = controller_get_interface()->supports_secure_connections();
2587         /* acceptor receives service connection establishment Request for */
2588         /* Secure Connections Only service */
2589         if (!(local_supports_sc) || !(p_dev_rec->remote_supports_secure_connections))
2590         {
2591             BTM_TRACE_DEBUG("%s: SC only service,local_support_for_sc %d,",
2592                             "remote_support_for_sc %d: fail pairing",__FUNCTION__,
2593                             local_supports_sc, p_dev_rec->remote_supports_secure_connections);
2594
2595             if (p_callback)
2596                 (*p_callback) (bd_addr, transport, (void *)p_ref_data,
2597                                BTM_MODE4_LEVEL4_NOT_SUPPORTED);
2598
2599             return (BTM_MODE4_LEVEL4_NOT_SUPPORTED);
2600         }
2601     }
2602
2603     p_dev_rec->p_cur_service     = p_serv_rec;
2604     p_dev_rec->security_required = security_required;
2605
2606     if (btm_cb.security_mode == BTM_SEC_MODE_SP ||
2607         btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
2608         btm_cb.security_mode == BTM_SEC_MODE_SC)
2609     {
2610         if (BTM_SEC_IS_SM4(p_dev_rec->sm4))
2611         {
2612             if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) &&
2613                 (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
2614             {
2615                 /* BTM_LKEY_TYPE_AUTH_COMB_P_256 is the only acceptable key in this case */
2616                 if ((p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) != 0)
2617                 {
2618                     p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
2619                 }
2620
2621                 p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
2622                                           BTM_SEC_AUTHENTICATED);
2623                 BTM_TRACE_DEBUG("%s: sec_flags:0x%x", __FUNCTION__, p_dev_rec->sec_flags);
2624             }
2625             else
2626             {
2627                 /* If we already have a link key, check if that link key is good enough */
2628                 btm_sec_check_upgrade(p_dev_rec, is_originator);
2629             }
2630         }
2631     }
2632
2633     p_dev_rec->is_originator     = is_originator;
2634     p_dev_rec->p_callback        = p_callback;
2635     p_dev_rec->p_ref_data        = p_ref_data;
2636
2637     /* Although authentication and encryption are per connection */
2638     /* authorization is per access request.  For example when serial connection */
2639     /* is up and authorized and client requests to read file (access to other */
2640     /* scn, we need to request user's permission again. */
2641     p_dev_rec->sec_flags &= ~(BTM_SEC_AUTHORIZED);
2642
2643     BTM_TRACE_EVENT ("%s() proto_id:%d chan_id:%d State:%d Flags:0x%x Required:0x%x Service ID:%d",
2644                       __func__, mx_proto_id, mx_chan_id, p_dev_rec->sec_state, p_dev_rec->sec_flags,
2645                       p_dev_rec->security_required, p_dev_rec->p_cur_service->service_id);
2646
2647     if ((rc = btm_sec_execute_procedure (p_dev_rec)) != BTM_CMD_STARTED)
2648     {
2649         if (p_callback)
2650         {
2651             p_dev_rec->p_callback = NULL;
2652             (*p_callback) (bd_addr,transport, p_ref_data, (UINT8)rc);
2653         }
2654     }
2655
2656     return rc;
2657 }
2658
2659 /*******************************************************************************
2660 **
2661 ** Function         btm_sec_conn_req
2662 **
2663 ** Description      This function is when the peer device is requesting
2664 **                  connection
2665 **
2666 ** Returns          void
2667 **
2668 *******************************************************************************/
2669 void btm_sec_conn_req (UINT8 *bda, UINT8 *dc)
2670 {
2671     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (bda);
2672
2673     /* Some device may request a connection before we are done with the HCI_Reset sequence */
2674     if (!controller_get_interface()->get_is_ready())
2675     {
2676         BTM_TRACE_EVENT ("Security Manager: connect request when device not ready");
2677         btsnd_hcic_reject_conn (bda, HCI_ERR_HOST_REJECT_DEVICE);
2678         return;
2679     }
2680
2681     /* Security guys wants us not to allow connection from not paired devices */
2682
2683     /* Check if connection is allowed for only paired devices */
2684     if (btm_cb.connect_only_paired)
2685     {
2686         if (!p_dev_rec || !(p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED))
2687         {
2688             BTM_TRACE_EVENT ("Security Manager: connect request from non-paired device");
2689             btsnd_hcic_reject_conn (bda, HCI_ERR_HOST_REJECT_DEVICE);
2690             return;
2691         }
2692     }
2693
2694 #if BTM_ALLOW_CONN_IF_NONDISCOVER == FALSE
2695     /* If non-discoverable, only allow known devices to connect */
2696     if (btm_cb.btm_inq_vars.discoverable_mode == BTM_NON_DISCOVERABLE)
2697     {
2698         if (!p_dev_rec)
2699         {
2700             BTM_TRACE_EVENT ("Security Manager: connect request from not paired device");
2701             btsnd_hcic_reject_conn (bda, HCI_ERR_HOST_REJECT_DEVICE);
2702             return;
2703         }
2704     }
2705 #endif
2706
2707     if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
2708         &&(btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
2709         &&(!memcmp (btm_cb.pairing_bda, bda, BD_ADDR_LEN)))
2710     {
2711         BTM_TRACE_EVENT ("Security Manager: reject connect request from bonding device");
2712
2713         /* incoming connection from bonding device is rejected */
2714         btm_cb.pairing_flags |= BTM_PAIR_FLAGS_REJECTED_CONNECT;
2715         btsnd_hcic_reject_conn (bda, HCI_ERR_HOST_REJECT_DEVICE);
2716         return;
2717     }
2718
2719     /* Host is not interested or approved connection.  Save BDA and DC and */
2720     /* pass request to L2CAP */
2721     memcpy (btm_cb.connecting_bda, bda, BD_ADDR_LEN);
2722     memcpy (btm_cb.connecting_dc,  dc,  DEV_CLASS_LEN);
2723
2724     if (l2c_link_hci_conn_req (bda))
2725     {
2726         if (!p_dev_rec)
2727         {
2728             /* accept the connection -> allocate a device record */
2729             p_dev_rec = btm_sec_alloc_dev (bda);
2730         }
2731         if (p_dev_rec)
2732         {
2733             p_dev_rec->sm4 |= BTM_SM4_CONN_PEND;
2734         }
2735     }
2736 }
2737
2738 /*******************************************************************************
2739 **
2740 ** Function         btm_sec_bond_cancel_complete
2741 **
2742 ** Description      This function is called to report bond cancel complete
2743 **                  event.
2744 **
2745 ** Returns          void
2746 **
2747 *******************************************************************************/
2748 static void btm_sec_bond_cancel_complete (void)
2749 {
2750     tBTM_SEC_DEV_REC *p_dev_rec;
2751
2752     if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) ||
2753         (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_cb.pairing_state &&
2754          BTM_PAIR_FLAGS_WE_STARTED_DD & btm_cb.pairing_flags) ||
2755          (btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME &&
2756           BTM_PAIR_FLAGS_WE_CANCEL_DD & btm_cb.pairing_flags))
2757     {
2758         /* for dedicated bonding in legacy mode, authentication happens at "link level"
2759          * btm_sec_connected is called with failed status.
2760          * In theory, the code that handles is_pairing_device/TRUE should clean out security related code.
2761          * However, this function may clean out the security related flags and btm_sec_connected would not know
2762          * this function also needs to do proper clean up.
2763          */
2764         if ((p_dev_rec = btm_find_dev (btm_cb.pairing_bda)) != NULL)
2765             p_dev_rec->security_required = BTM_SEC_NONE;
2766         btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
2767
2768         /* Notify application that the cancel succeeded */
2769         if (btm_cb.api.p_bond_cancel_cmpl_callback)
2770             btm_cb.api.p_bond_cancel_cmpl_callback(BTM_SUCCESS);
2771     }
2772 }
2773
2774 /*******************************************************************************
2775 **
2776 ** Function         btm_create_conn_cancel_complete
2777 **
2778 ** Description      This function is called when the command complete message
2779 **                  is received from the HCI for the create connection cancel
2780 **                  command.
2781 **
2782 ** Returns          void
2783 **
2784 *******************************************************************************/
2785 void btm_create_conn_cancel_complete (UINT8 *p)
2786 {
2787     UINT8       status;
2788
2789     STREAM_TO_UINT8 (status, p);
2790     BTM_TRACE_EVENT ("btm_create_conn_cancel_complete(): in State: %s  status:%d",
2791                       btm_pair_state_descr(btm_cb.pairing_state), status);
2792
2793     /* if the create conn cancel cmd was issued by the bond cancel,
2794     ** the application needs to be notified that bond cancel succeeded
2795     */
2796     switch (status)
2797     {
2798         case HCI_SUCCESS:
2799             btm_sec_bond_cancel_complete();
2800             break;
2801         case HCI_ERR_CONNECTION_EXISTS:
2802         case HCI_ERR_NO_CONNECTION:
2803         default:
2804             /* Notify application of the error */
2805             if (btm_cb.api.p_bond_cancel_cmpl_callback)
2806                 btm_cb.api.p_bond_cancel_cmpl_callback(BTM_ERR_PROCESSING);
2807             break;
2808     }
2809 }
2810
2811 /*******************************************************************************
2812 **
2813 ** Function         btm_sec_check_pending_reqs
2814 **
2815 ** Description      This function is called at the end of the security procedure
2816 **                  to let L2CAP and RFCOMM know to re-submit any pending requests
2817 **
2818 ** Returns          void
2819 **
2820 *******************************************************************************/
2821 void btm_sec_check_pending_reqs (void)
2822 {
2823     tBTM_SEC_QUEUE_ENTRY    *p_e;
2824     BUFFER_Q                bq;
2825
2826     if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
2827     {
2828         /* First, resubmit L2CAP requests */
2829         if (btm_cb.sec_req_pending)
2830         {
2831             btm_cb.sec_req_pending = FALSE;
2832             l2cu_resubmit_pending_sec_req (NULL);
2833         }
2834
2835         /* Now, re-submit anything in the mux queue */
2836         bq = btm_cb.sec_pending_q;
2837
2838         GKI_init_q (&btm_cb.sec_pending_q);
2839
2840         while ((p_e = (tBTM_SEC_QUEUE_ENTRY *)GKI_dequeue (&bq)) != NULL)
2841         {
2842             /* Check that the ACL is still up before starting security procedures */
2843             if (btm_bda_to_acl(p_e->bd_addr, p_e->transport) != NULL)
2844             {
2845                 if (p_e->psm != 0)
2846                 {
2847                     BTM_TRACE_EVENT("%s PSM:0x%04x Is_Orig:%u mx_proto_id:%u mx_chan_id:%u",
2848                                     __FUNCTION__, p_e->psm, p_e->is_orig,
2849                                     p_e->mx_proto_id, p_e->mx_chan_id);
2850
2851                     btm_sec_mx_access_request (p_e->bd_addr, p_e->psm, p_e->is_orig,
2852                                            p_e->mx_proto_id, p_e->mx_chan_id,
2853                                            p_e->p_callback, p_e->p_ref_data);
2854                 }
2855                 else
2856                 {
2857                     BTM_SetEncryption(p_e->bd_addr, p_e->transport, p_e->p_callback,
2858                                       p_e->p_ref_data);
2859                 }
2860             }
2861
2862             GKI_freebuf (p_e);
2863         }
2864     }
2865 }
2866
2867 /*******************************************************************************
2868 **
2869 ** Function         btm_sec_init
2870 **
2871 ** Description      This function is on the SEC startup
2872 **
2873 ** Returns          void
2874 **
2875 *******************************************************************************/
2876 void btm_sec_init (UINT8 sec_mode)
2877 {
2878     btm_cb.security_mode = sec_mode;
2879     memset (btm_cb.pairing_bda, 0xff, BD_ADDR_LEN);
2880     btm_cb.max_collision_delay = BTM_SEC_MAX_COLLISION_DELAY;
2881 }
2882
2883 /*******************************************************************************
2884 **
2885 ** Function         btm_sec_device_down
2886 **
2887 ** Description      This function should be called when device is disabled or
2888 **                  turned off
2889 **
2890 ** Returns          void
2891 **
2892 *******************************************************************************/
2893 void btm_sec_device_down (void)
2894 {
2895     BTM_TRACE_EVENT ("%s() State: %s", __func__, btm_pair_state_descr(btm_cb.pairing_state));
2896     btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
2897 }
2898
2899 /*******************************************************************************
2900 **
2901 ** Function         btm_sec_dev_reset
2902 **
2903 ** Description      This function should be called after device reset
2904 **
2905 ** Returns          void
2906 **
2907 *******************************************************************************/
2908 void btm_sec_dev_reset (void)
2909 {
2910     if (controller_get_interface()->supports_simple_pairing())
2911     {
2912         /* set the default IO capabilities */
2913         btm_cb.devcb.loc_io_caps = BTM_LOCAL_IO_CAPS;
2914         /* add mx service to use no security */
2915         BTM_SetSecurityLevel(FALSE, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX,
2916                              BTM_SEC_NONE, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0);
2917     }
2918     else
2919     {
2920         btm_cb.security_mode = BTM_SEC_MODE_SERVICE;
2921     }
2922
2923     BTM_TRACE_DEBUG ("btm_sec_dev_reset sec mode: %d", btm_cb.security_mode);
2924 }
2925
2926 /*******************************************************************************
2927 **
2928 ** Function         btm_sec_abort_access_req
2929 **
2930 ** Description      This function is called by the L2CAP or RFCOMM to abort
2931 **                  the pending operation.
2932 **
2933 ** Parameters:      bd_addr       - Address of the peer device
2934 **
2935 ** Returns          void
2936 **
2937 *******************************************************************************/
2938 void btm_sec_abort_access_req (BD_ADDR bd_addr)
2939 {
2940     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev (bd_addr);
2941
2942     if (!p_dev_rec)
2943         return;
2944
2945     if ((p_dev_rec->sec_state != BTM_SEC_STATE_AUTHORIZING)
2946         && (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING))
2947         return;
2948
2949     p_dev_rec->sec_state  = BTM_SEC_STATE_IDLE;
2950     p_dev_rec->p_callback = NULL;
2951 }
2952
2953 /*******************************************************************************
2954 **
2955 ** Function         btm_sec_dd_create_conn
2956 **
2957 ** Description      This function is called to create the ACL connection for
2958 **                  the dedicated boding process
2959 **
2960 ** Returns          void
2961 **
2962 *******************************************************************************/
2963 static tBTM_STATUS btm_sec_dd_create_conn (tBTM_SEC_DEV_REC *p_dev_rec)
2964 {
2965     tL2C_LCB         *p_lcb;
2966
2967     /* Make sure an L2cap link control block is available */
2968     if ((p_lcb = l2cu_allocate_lcb (p_dev_rec->bd_addr, TRUE, BT_TRANSPORT_BR_EDR)) == NULL)
2969     {
2970         BTM_TRACE_WARNING ("Security Manager: failed allocate LCB [%02x%02x%02x%02x%02x%02x]",
2971                             p_dev_rec->bd_addr[0], p_dev_rec->bd_addr[1], p_dev_rec->bd_addr[2],
2972                             p_dev_rec->bd_addr[3], p_dev_rec->bd_addr[4], p_dev_rec->bd_addr[5]);
2973
2974         return(BTM_NO_RESOURCES);
2975     }
2976
2977     /* set up the control block to indicated dedicated bonding */
2978     btm_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE;
2979
2980     if (l2cu_create_conn(p_lcb, BT_TRANSPORT_BR_EDR) == FALSE)
2981     {
2982         BTM_TRACE_WARNING ("Security Manager: failed create  [%02x%02x%02x%02x%02x%02x]",
2983                             p_dev_rec->bd_addr[0], p_dev_rec->bd_addr[1], p_dev_rec->bd_addr[2],
2984                             p_dev_rec->bd_addr[3], p_dev_rec->bd_addr[4], p_dev_rec->bd_addr[5]);
2985
2986         l2cu_release_lcb(p_lcb);
2987         return(BTM_NO_RESOURCES);
2988     }
2989
2990     btm_acl_update_busy_level (BTM_BLI_PAGE_EVT);
2991
2992     BTM_TRACE_DEBUG ("Security Manager: btm_sec_dd_create_conn [%02x%02x%02x%02x%02x%02x]",
2993                       p_dev_rec->bd_addr[0], p_dev_rec->bd_addr[1], p_dev_rec->bd_addr[2],
2994                       p_dev_rec->bd_addr[3], p_dev_rec->bd_addr[4], p_dev_rec->bd_addr[5]);
2995
2996     btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
2997
2998     return(BTM_CMD_STARTED);
2999 }
3000
3001 /*******************************************************************************
3002 **
3003 ** Function         btm_sec_rmt_name_request_complete
3004 **
3005 ** Description      This function is called when remote name was obtained from
3006 **                  the peer device
3007 **
3008 ** Returns          void
3009 **
3010 *******************************************************************************/
3011 void btm_sec_rmt_name_request_complete (UINT8 *p_bd_addr, UINT8 *p_bd_name, UINT8 status)
3012 {
3013     tBTM_SEC_DEV_REC *p_dev_rec;
3014     int              i;
3015     DEV_CLASS        dev_class;
3016     UINT8            old_sec_state;
3017
3018     BTM_TRACE_EVENT ("btm_sec_rmt_name_request_complete");
3019     if (((p_bd_addr == NULL) && !BTM_ACL_IS_CONNECTED(btm_cb.connecting_bda))
3020         || ((p_bd_addr != NULL) && !BTM_ACL_IS_CONNECTED(p_bd_addr)))
3021     {
3022         btm_acl_resubmit_page();
3023     }
3024
3025     /* If remote name request failed, p_bd_addr is null and we need to search */
3026     /* based on state assuming that we are doing 1 at a time */
3027     if (p_bd_addr)
3028         p_dev_rec = btm_find_dev (p_bd_addr);
3029     else
3030     {
3031         p_dev_rec = &btm_cb.sec_dev_rec[0];
3032
3033         for (i = 0; i < BTM_SEC_MAX_DEVICE_RECORDS; i++, p_dev_rec++)
3034         {
3035             if ((p_dev_rec->sec_flags & BTM_SEC_IN_USE)
3036                 && (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME))
3037             {
3038                 p_bd_addr = p_dev_rec->bd_addr;
3039                 break;
3040             }
3041         }
3042
3043         if (i == BTM_SEC_MAX_DEVICE_RECORDS)
3044             p_dev_rec = NULL;
3045     }
3046
3047
3048     /* Commenting out trace due to obf/compilation problems.
3049     */
3050 #if (BT_USE_TRACES == TRUE)
3051     if (!p_bd_name)
3052         p_bd_name = (UINT8 *)"";
3053
3054     if (p_dev_rec)
3055     {
3056         BTM_TRACE_EVENT ("Security Manager: rmt_name_complete PairState: %s  RemName: %s  status: %d State:%d  p_dev_rec: 0x%08x ",
3057                           btm_pair_state_descr (btm_cb.pairing_state), p_bd_name,
3058                           status, p_dev_rec->sec_state, p_dev_rec);
3059     }
3060     else
3061     {
3062         BTM_TRACE_EVENT ("Security Manager: rmt_name_complete PairState: %s  RemName: %s  status: %d",
3063                           btm_pair_state_descr (btm_cb.pairing_state), p_bd_name,
3064                           status);
3065     }
3066 #endif
3067
3068     if (p_dev_rec)
3069     {
3070         old_sec_state = p_dev_rec->sec_state;
3071         if (status == HCI_SUCCESS)
3072         {
3073             BCM_STRNCPY_S ((char *)p_dev_rec->sec_bd_name, sizeof (p_dev_rec->sec_bd_name), (char *)p_bd_name, BTM_MAX_REM_BD_NAME_LEN);
3074             p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
3075             BTM_TRACE_EVENT ("setting BTM_SEC_NAME_KNOWN sec_flags:0x%x", p_dev_rec->sec_flags);
3076         }
3077         else
3078         {
3079             /* Notify all clients waiting for name to be resolved even if it failed so clients can continue */
3080             p_dev_rec->sec_bd_name[0] = 0;
3081         }
3082
3083         if (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME)
3084             p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
3085
3086         /* Notify all clients waiting for name to be resolved */
3087         for (i = 0;i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++)
3088         {
3089             if (btm_cb.p_rmt_name_callback[i] && p_bd_addr)
3090                 (*btm_cb.p_rmt_name_callback[i])(p_bd_addr, p_dev_rec->dev_class,
3091                                                  p_dev_rec->sec_bd_name);
3092         }
3093     }
3094     else
3095     {
3096         dev_class[0] = 0;
3097         dev_class[1] = 0;
3098         dev_class[2] = 0;
3099
3100         /* Notify all clients waiting for name to be resolved even if not found so clients can continue */
3101         for (i = 0;i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++)
3102         {
3103             if (btm_cb.p_rmt_name_callback[i] && p_bd_addr)
3104                 (*btm_cb.p_rmt_name_callback[i])(p_bd_addr, dev_class, (UINT8 *)"");
3105         }
3106
3107         return;
3108     }
3109
3110     /* If we were delaying asking UI for a PIN because name was not resolved, ask now */
3111     if ( (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_LOCAL_PIN) && p_bd_addr
3112          &&  (memcmp (btm_cb.pairing_bda, p_bd_addr, BD_ADDR_LEN) == 0) )
3113     {
3114         BTM_TRACE_EVENT ("btm_sec_rmt_name_request_complete() delayed pin now being requested flags:0x%x, (p_pin_callback=0x%p)", btm_cb.pairing_flags, btm_cb.api.p_pin_callback);
3115
3116         if (((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) == 0) &&
3117             ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0) &&
3118             btm_cb.api.p_pin_callback)
3119         {
3120             BTM_TRACE_EVENT ("btm_sec_rmt_name_request_complete() calling pin_callback");
3121             btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
3122             (*btm_cb.api.p_pin_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, p_bd_name);
3123         }
3124
3125         /* Set the same state again to force the timer to be restarted */
3126         btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN);
3127         return;
3128     }
3129
3130     /* Check if we were delaying bonding because name was not resolved */
3131     if ( btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME)
3132     {
3133         if (p_bd_addr && memcmp (btm_cb.pairing_bda, p_bd_addr, BD_ADDR_LEN) == 0)
3134         {
3135             BTM_TRACE_EVENT ("btm_sec_rmt_name_request_complete() continue bonding sm4: 0x%04x, status:0x%x", p_dev_rec->sm4, status);
3136             if(btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_CANCEL_DD)
3137             {
3138                 btm_sec_bond_cancel_complete();
3139                 return;
3140             }
3141
3142             if (status != HCI_SUCCESS)
3143             {
3144                 btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
3145
3146                 if (btm_cb.api.p_auth_complete_callback)
3147                     (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,  p_dev_rec->dev_class,
3148                                                             p_dev_rec->sec_bd_name, status);
3149                 return;
3150             }
3151
3152             /* if peer is very old legacy devices, HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is not reported */
3153             if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4))
3154             {
3155                 /* set the KNOWN flag only if BTM_PAIR_FLAGS_REJECTED_CONNECT is not set.*/
3156                 /* If it is set, there may be a race condition */
3157                 BTM_TRACE_DEBUG ("btm_sec_rmt_name_request_complete  IS_SM4_UNKNOWN Flags:0x%04x",
3158                                    btm_cb.pairing_flags);
3159                 if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0)
3160                 {
3161                     p_dev_rec->sm4 |= BTM_SM4_KNOWN;
3162                 }
3163             }
3164
3165             BTM_TRACE_DEBUG("%s, SM4 Value: %x, Legacy:%d,IS SM4:%d, Unknown:%d",__FUNCTION__,
3166                 p_dev_rec->sm4, BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4),
3167                 BTM_SEC_IS_SM4(p_dev_rec->sm4),BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4));
3168
3169             /* BT 2.1 or carkit, bring up the connection to force the peer to request PIN.
3170             ** Else prefetch (btm_sec_check_prefetch_pin will do the prefetching if needed)
3171             */
3172             if ((p_dev_rec->sm4 != BTM_SM4_KNOWN) || !btm_sec_check_prefetch_pin(p_dev_rec))
3173             {
3174                 /* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */
3175                 /*  before originating  */
3176                 if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)
3177                 {
3178                     BTM_TRACE_WARNING ("btm_sec_rmt_name_request_complete: waiting HCI_Connection_Complete after rejecting connection");
3179                 }
3180                 /* Both we and the peer are 2.1 - continue to create connection */
3181                 else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED)
3182                 {
3183                     BTM_TRACE_WARNING ("btm_sec_rmt_name_request_complete: failed to start connection");
3184
3185                     btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
3186
3187                     if (btm_cb.api.p_auth_complete_callback)
3188                     (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,  p_dev_rec->dev_class,
3189                                                             p_dev_rec->sec_bd_name, HCI_ERR_MEMORY_FULL);
3190                 }
3191             }
3192             return;
3193         }
3194         else
3195         {
3196             BTM_TRACE_WARNING ("btm_sec_rmt_name_request_complete: wrong BDA, retry with pairing BDA");
3197
3198             BTM_ReadRemoteDeviceName (btm_cb.pairing_bda, NULL, BT_TRANSPORT_BR_EDR);
3199             return;
3200         }
3201     }
3202
3203     /* check if we were delaying link_key_callback because name was not resolved */
3204     if (p_dev_rec->link_key_not_sent)
3205     {
3206         /* If HCI connection complete has not arrived, wait for it */
3207         if (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE)
3208             return;
3209
3210         p_dev_rec->link_key_not_sent = FALSE;
3211         btm_send_link_key_notif(p_dev_rec);
3212
3213         /* If its not us who perform authentication, we should tell stackserver */
3214         /* that some authentication has been completed                          */
3215         /* This is required when different entities receive link notification and auth complete */
3216         if (!(p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE))
3217         {
3218             if (btm_cb.api.p_auth_complete_callback)
3219                 (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
3220                                                         p_dev_rec->dev_class,
3221                                                         p_dev_rec->sec_bd_name, HCI_SUCCESS);
3222
3223         }
3224     }
3225
3226     /* If this is a bonding procedure can disconnect the link now */
3227     if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
3228         && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))
3229     {
3230         BTM_TRACE_WARNING ("btm_sec_rmt_name_request_complete (none/ce)");
3231         p_dev_rec->security_required &= ~(BTM_SEC_OUT_AUTHENTICATE);
3232         l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
3233         return;
3234     }
3235
3236     if (old_sec_state != BTM_SEC_STATE_GETTING_NAME)
3237         return;
3238
3239     /* If get name failed, notify the waiting layer */
3240     if (status != HCI_SUCCESS)
3241     {
3242         btm_sec_dev_rec_cback_event  (p_dev_rec, BTM_ERR_PROCESSING, FALSE);
3243         return;
3244     }
3245
3246     if (p_dev_rec->sm4 & BTM_SM4_REQ_PEND)
3247     {
3248         BTM_TRACE_EVENT ("waiting for remote features!!");
3249         return;
3250     }
3251
3252     /* Remote Name succeeded, execute the next security procedure, if any */
3253     status = (UINT8)btm_sec_execute_procedure (p_dev_rec);
3254
3255     /* If result is pending reply from the user or from the device is pending */
3256     if (status == BTM_CMD_STARTED)
3257         return;
3258
3259     /* There is no next procedure or start of procedure failed, notify the waiting layer */
3260     btm_sec_dev_rec_cback_event  (p_dev_rec, status, FALSE);
3261 }
3262
3263 /*******************************************************************************
3264 **
3265 ** Function         btm_sec_rmt_host_support_feat_evt
3266 **
3267 ** Description      This function is called when the
3268 **                  HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is received
3269 **
3270 ** Returns          void
3271 **
3272 *******************************************************************************/
3273 void btm_sec_rmt_host_support_feat_evt (UINT8 *p)
3274 {
3275     tBTM_SEC_DEV_REC *p_dev_rec;
3276     BD_ADDR         bd_addr;        /* peer address */
3277     BD_FEATURES     features;
3278
3279     STREAM_TO_BDADDR (bd_addr, p);
3280     p_dev_rec = btm_find_or_alloc_dev (bd_addr);
3281
3282     BTM_TRACE_EVENT ("btm_sec_rmt_host_support_feat_evt  sm4: 0x%x  p[0]: 0x%x", p_dev_rec->sm4, p[0]);
3283
3284     if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4))
3285     {
3286         p_dev_rec->sm4 = BTM_SM4_KNOWN;
3287         STREAM_TO_ARRAY(features, p, HCI_FEATURE_BYTES_PER_PAGE);
3288         if (HCI_SSP_HOST_SUPPORTED(features))
3289         {
3290             p_dev_rec->sm4 = BTM_SM4_TRUE;
3291         }
3292         BTM_TRACE_EVENT ("btm_sec_rmt_host_support_feat_evt sm4: 0x%x features[0]: 0x%x", p_dev_rec->sm4, features[0]);
3293     }
3294 }
3295
3296 /*******************************************************************************
3297 **
3298 ** Function         btm_io_capabilities_req
3299 **
3300 ** Description      This function is called when LM request for the IO
3301 **                  capability of the local device and
3302 **                  if the OOB data is present for the device in the event
3303 **
3304 ** Returns          void
3305 **
3306 *******************************************************************************/
3307 void btm_io_capabilities_req (UINT8 *p)
3308 {
3309     tBTM_SP_IO_REQ  evt_data;
3310     UINT8           err_code = 0;
3311     tBTM_SEC_DEV_REC *p_dev_rec;
3312     BOOLEAN         is_orig = TRUE;
3313     UINT8           callback_rc = BTM_SUCCESS;
3314
3315     STREAM_TO_BDADDR (evt_data.bd_addr, p);
3316
3317     /* setup the default response according to compile options */
3318     /* assume that the local IO capability does not change
3319      * loc_io_caps is initialized with the default value */
3320     evt_data.io_cap = btm_cb.devcb.loc_io_caps;
3321     evt_data.oob_data = BTM_OOB_NONE;
3322     evt_data.auth_req = BTM_DEFAULT_AUTH_REQ;
3323
3324     BTM_TRACE_EVENT("%s: State: %s", __FUNCTION__, btm_pair_state_descr(btm_cb.pairing_state));
3325
3326     p_dev_rec = btm_find_or_alloc_dev (evt_data.bd_addr);
3327
3328     BTM_TRACE_DEBUG("%s:Security mode: %d, Num Read Remote Feat pages: %d", __FUNCTION__,
3329                       btm_cb.security_mode, p_dev_rec->num_read_pages);
3330
3331     if ((btm_cb.security_mode == BTM_SEC_MODE_SC) && (p_dev_rec->num_read_pages == 0))
3332     {
3333         BTM_TRACE_EVENT("%s: Device security mode is SC only.",
3334                          "To continue need to know remote features.", __FUNCTION__);
3335
3336         p_dev_rec->remote_features_needed = TRUE;
3337         return;
3338     }
3339
3340     p_dev_rec->sm4 |= BTM_SM4_TRUE;
3341
3342     BTM_TRACE_EVENT("%s: State: %s  Flags: 0x%04x  p_cur_service: 0x%08x",
3343                      __FUNCTION__, btm_pair_state_descr(btm_cb.pairing_state),
3344                      btm_cb.pairing_flags, p_dev_rec->p_cur_service);
3345
3346     if (p_dev_rec->p_cur_service)
3347     {
3348         BTM_TRACE_EVENT("%s: cur_service psm: 0x%04x, security_flags: 0x%04x",
3349                          __FUNCTION__, p_dev_rec->p_cur_service->psm,
3350                          p_dev_rec->p_cur_service->security_flags);
3351     }
3352
3353     switch (btm_cb.pairing_state)
3354     {
3355         /* initiator connecting */
3356         case BTM_PAIR_STATE_IDLE:
3357             //TODO: Handle Idle pairing state
3358             //security_required = p_dev_rec->security_required;
3359             break;
3360
3361         /* received IO capability response already->acceptor */
3362         case BTM_PAIR_STATE_INCOMING_SSP:
3363             is_orig = FALSE;
3364
3365             if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD)
3366             {
3367                 /* acceptor in dedicated bonding */
3368                 evt_data.auth_req = BTM_DEFAULT_DD_AUTH_REQ;
3369             }
3370             break;
3371
3372         /* initiator, at this point it is expected to be dedicated bonding
3373         initiated by local device */
3374         case BTM_PAIR_STATE_WAIT_PIN_REQ:
3375             if (!memcmp (evt_data.bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN))
3376             {
3377                 evt_data.auth_req = BTM_DEFAULT_DD_AUTH_REQ;
3378             }
3379             else
3380             {
3381                 err_code = HCI_ERR_HOST_BUSY_PAIRING;
3382             }
3383             break;
3384
3385         /* any other state is unexpected */
3386         default:
3387             err_code = HCI_ERR_HOST_BUSY_PAIRING;
3388             BTM_TRACE_ERROR("%s: Unexpected Pairing state received %d", __FUNCTION__,
3389                              btm_cb.pairing_state);
3390             break;
3391     }
3392
3393     if (btm_cb.pairing_disabled)
3394     {
3395         /* pairing is not allowed */
3396         BTM_TRACE_DEBUG("%s: Pairing is not allowed -> fail pairing.", __FUNCTION__);
3397         err_code = HCI_ERR_PAIRING_NOT_ALLOWED;
3398     }
3399     else if (btm_cb.security_mode == BTM_SEC_MODE_SC)
3400     {
3401         BOOLEAN local_supports_sc = controller_get_interface()->supports_secure_connections();
3402         /* device in Secure Connections Only mode */
3403         if (!(local_supports_sc) || !(p_dev_rec->remote_supports_secure_connections))
3404         {
3405             BTM_TRACE_DEBUG("%s: SC only service, local_support_for_sc %d,",
3406                             " remote_support_for_sc 0x%02x -> fail pairing", __FUNCTION__,
3407                             local_supports_sc, p_dev_rec->remote_supports_secure_connections);
3408
3409             err_code = HCI_ERR_PAIRING_NOT_ALLOWED;
3410         }
3411     }
3412
3413     if (err_code != 0)
3414     {
3415 /* coverity[uninit_use_in_call]
3416 Event uninit_use_in_call: Using uninitialized element of array "evt_data.bd_addr" in call to function "memcmp"
3417 False-positive: evt_data.bd_addr is set at the beginning with:     STREAM_TO_BDADDR (evt_data.bd_addr, p);
3418 */
3419         btsnd_hcic_io_cap_req_neg_reply(evt_data.bd_addr, err_code);
3420         return;
3421     }
3422
3423     evt_data.is_orig = is_orig;
3424
3425     if (is_orig)
3426     {
3427         /* local device initiated the pairing non-bonding -> use p_cur_service */
3428         if (!(btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
3429             p_dev_rec->p_cur_service &&
3430             (p_dev_rec->p_cur_service->security_flags & BTM_SEC_OUT_AUTHENTICATE))
3431         {
3432             if (btm_cb.security_mode == BTM_SEC_MODE_SC)
3433             {
3434                 /* SC only mode device requires MITM protection */
3435                 evt_data.auth_req = BTM_AUTH_SP_YES;
3436             }
3437             else
3438             {
3439                 evt_data.auth_req = (p_dev_rec->p_cur_service->security_flags &
3440                                      BTM_SEC_OUT_MITM)? BTM_AUTH_SP_YES : BTM_AUTH_SP_NO;
3441             }
3442         }
3443     }
3444
3445     /* Notify L2CAP to increase timeout */
3446     l2c_pin_code_request (evt_data.bd_addr);
3447
3448     memcpy (btm_cb.pairing_bda, evt_data.bd_addr, BD_ADDR_LEN);
3449
3450 /* coverity[uninit_use_in_call]
3451 Event uninit_use_in_call: Using uninitialized element of array "evt_data.bd_addr" in call to function "memcmp"
3452 False-positive: False-positive: evt_data.bd_addr is set at the beginning with:     STREAM_TO_BDADDR (evt_data.bd_addr, p);
3453 */
3454     if (!memcmp (evt_data.bd_addr, btm_cb.connecting_bda, BD_ADDR_LEN))
3455         memcpy (p_dev_rec->dev_class, btm_cb.connecting_dc, DEV_CLASS_LEN);
3456
3457     btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS);
3458
3459     callback_rc = BTM_SUCCESS;
3460     if (p_dev_rec->sm4 & BTM_SM4_UPGRADE)
3461     {
3462         p_dev_rec->sm4 &= ~BTM_SM4_UPGRADE;
3463
3464         /* link key upgrade: always use SPGB_YES - assuming we want to save the link key */
3465         evt_data.auth_req = BTM_AUTH_SPGB_YES;
3466     }
3467     else if (btm_cb.api.p_sp_callback)
3468     {
3469         /* the callback function implementation may change the IO capability... */
3470         callback_rc = (*btm_cb.api.p_sp_callback) (BTM_SP_IO_REQ_EVT, (tBTM_SP_EVT_DATA *)&evt_data);
3471     }
3472
3473 #if BTM_OOB_INCLUDED == TRUE
3474     if ((callback_rc == BTM_SUCCESS) || (BTM_OOB_UNKNOWN != evt_data.oob_data))
3475 #else
3476     if (callback_rc == BTM_SUCCESS)
3477 #endif
3478     {
3479         if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD))
3480         {
3481             evt_data.auth_req = (BTM_AUTH_DD_BOND | (evt_data.auth_req & BTM_AUTH_YN_BIT));
3482         }
3483
3484         if (btm_cb.security_mode == BTM_SEC_MODE_SC)
3485         {
3486             /* At this moment we know that both sides are SC capable, device in */
3487             /* SC only mode requires MITM for any service so let's set MITM bit */
3488             evt_data.auth_req |= BTM_AUTH_YN_BIT;
3489             BTM_TRACE_DEBUG("%s: for device in \"SC only\" mode set auth_req to 0x%02x",
3490                              __FUNCTION__, evt_data.auth_req);
3491         }
3492
3493         /* if the user does not indicate "reply later" by setting the oob_data to unknown */
3494         /* send the response right now. Save the current IO capability in the control block */
3495         btm_cb.devcb.loc_auth_req   = evt_data.auth_req;
3496         btm_cb.devcb.loc_io_caps    = evt_data.io_cap;
3497
3498         BTM_TRACE_EVENT("%s: State: %s  IO_CAP:%d oob_data:%d auth_req:%d",
3499                          __FUNCTION__, btm_pair_state_descr(btm_cb.pairing_state), evt_data.io_cap,
3500                          evt_data.oob_data, evt_data.auth_req);
3501
3502         btsnd_hcic_io_cap_req_reply(evt_data.bd_addr, evt_data.io_cap,
3503                                     evt_data.oob_data, evt_data.auth_req);
3504     }
3505 }
3506
3507 /*******************************************************************************
3508 **
3509 ** Function         btm_io_capabilities_rsp
3510 **
3511 ** Description      This function is called when the IO capability of the
3512 **                  specified device is received
3513 **
3514 ** Returns          void
3515 **
3516 *******************************************************************************/
3517 void btm_io_capabilities_rsp (UINT8 *p)
3518 {
3519     tBTM_SEC_DEV_REC *p_dev_rec;
3520     tBTM_SP_IO_RSP evt_data;
3521
3522     STREAM_TO_BDADDR (evt_data.bd_addr, p);
3523     STREAM_TO_UINT8 (evt_data.io_cap, p);
3524     STREAM_TO_UINT8 (evt_data.oob_data, p);
3525     STREAM_TO_UINT8 (evt_data.auth_req, p);
3526
3527     /* Allocate a new device record or reuse the oldest one */
3528     p_dev_rec = btm_find_or_alloc_dev (evt_data.bd_addr);
3529
3530     /* If no security is in progress, this indicates incoming security */
3531     if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
3532     {
3533         memcpy (btm_cb.pairing_bda, evt_data.bd_addr, BD_ADDR_LEN);
3534
3535         btm_sec_change_pairing_state (BTM_PAIR_STATE_INCOMING_SSP);
3536
3537         /* Make sure we reset the trusted mask to help against attacks */
3538         BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask);
3539
3540         /* work around for FW bug */
3541         btm_inq_stop_on_ssp();
3542     }
3543
3544     /* Notify L2CAP to increase timeout */
3545     l2c_pin_code_request (evt_data.bd_addr);
3546
3547     /* We must have a device record here.
3548      * Use the connecting device's CoD for the connection */
3549 /* coverity[uninit_use_in_call]
3550 Event uninit_use_in_call: Using uninitialized element of array "evt_data.bd_addr" in call to function "memcmp"
3551 FALSE-POSITIVE error from Coverity test-tool. evt_data.bd_addr is set at the beginning with:     STREAM_TO_BDADDR (evt_data.bd_addr, p);
3552 */
3553     if (!memcmp (evt_data.bd_addr, btm_cb.connecting_bda, BD_ADDR_LEN))
3554         memcpy (p_dev_rec->dev_class, btm_cb.connecting_dc, DEV_CLASS_LEN);
3555
3556     /* peer sets dedicated bonding bit and we did not initiate dedicated bonding */
3557     if (btm_cb.pairing_state == BTM_PAIR_STATE_INCOMING_SSP /* peer initiated bonding */
3558         && (evt_data.auth_req & BTM_AUTH_DD_BOND) )            /* and dedicated bonding bit is set */
3559     {
3560         btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PEER_STARTED_DD;
3561     }
3562
3563     /* save the IO capability in the device record */
3564     p_dev_rec->rmt_io_caps  = evt_data.io_cap;
3565     p_dev_rec->rmt_auth_req = evt_data.auth_req;
3566
3567     if (btm_cb.api.p_sp_callback)
3568         (*btm_cb.api.p_sp_callback) (BTM_SP_IO_RSP_EVT, (tBTM_SP_EVT_DATA *)&evt_data);
3569 }
3570
3571 /*******************************************************************************
3572 **
3573 ** Function         btm_proc_sp_req_evt
3574 **
3575 ** Description      This function is called to process/report
3576 **                  HCI_USER_CONFIRMATION_REQUEST_EVT
3577 **                  or HCI_USER_PASSKEY_REQUEST_EVT
3578 **                  or HCI_USER_PASSKEY_NOTIFY_EVT
3579 **
3580 ** Returns          void
3581 **
3582 *******************************************************************************/
3583 void btm_proc_sp_req_evt (tBTM_SP_EVT event, UINT8 *p)
3584 {
3585     tBTM_STATUS status = BTM_ERR_PROCESSING;
3586     tBTM_SP_EVT_DATA evt_data;
3587     UINT8               *p_bda = evt_data.cfm_req.bd_addr;
3588     tBTM_SEC_DEV_REC *p_dev_rec;
3589
3590     /* All events start with bd_addr */
3591     STREAM_TO_BDADDR (p_bda, p);
3592
3593     BTM_TRACE_EVENT ("btm_proc_sp_req_evt() BDA: %08x%04x event: 0x%x, State: %s",
3594                       (p_bda[0]<<24) + (p_bda[1]<<16) + (p_bda[2]<<8) + p_bda[3], (p_bda[4] << 8) + p_bda[5],
3595                       event, btm_pair_state_descr(btm_cb.pairing_state));
3596
3597     if ( ((p_dev_rec = btm_find_dev (p_bda)) != NULL)
3598          &&  (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
3599          &&  (memcmp (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN) == 0) )
3600     {
3601         memcpy (evt_data.cfm_req.bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN);
3602         memcpy (evt_data.cfm_req.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN);
3603
3604         BCM_STRNCPY_S ((char *)evt_data.cfm_req.bd_name, sizeof(evt_data.cfm_req.bd_name), (char *)p_dev_rec->sec_bd_name, BTM_MAX_REM_BD_NAME_LEN);
3605
3606         switch (event)
3607         {
3608             case BTM_SP_CFM_REQ_EVT:
3609                 /* Numeric confirmation. Need user to conf the passkey */
3610                 btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM);
3611
3612                 /* The device record must be allocated in the "IO cap exchange" step */
3613                 STREAM_TO_UINT32 (evt_data.cfm_req.num_val, p);
3614
3615                 evt_data.cfm_req.just_works = TRUE;
3616
3617                 /* process user confirm req in association with the auth_req param */
3618 #if (BTM_LOCAL_IO_CAPS == BTM_IO_CAP_IO)
3619                 if ( (p_dev_rec->rmt_io_caps == BTM_IO_CAP_IO)
3620                      &&  (btm_cb.devcb.loc_io_caps == BTM_IO_CAP_IO)
3621                      &&  ((p_dev_rec->rmt_auth_req & BTM_AUTH_SP_YES) || (btm_cb.devcb.loc_auth_req & BTM_AUTH_SP_YES)) )
3622                 {
3623                     /* Both devices are DisplayYesNo and one or both devices want to authenticate
3624                        -> use authenticated link key */
3625                     evt_data.cfm_req.just_works = FALSE;
3626                 }
3627 #endif
3628                 BTM_TRACE_DEBUG ("btm_proc_sp_req_evt()  just_works:%d, io loc:%d, rmt:%d, auth loc:%d, rmt:%d",
3629                                   evt_data.cfm_req.just_works, btm_cb.devcb.loc_io_caps, p_dev_rec->rmt_io_caps,
3630                                   btm_cb.devcb.loc_auth_req, p_dev_rec->rmt_auth_req);
3631
3632                 evt_data.cfm_req.loc_auth_req   = btm_cb.devcb.loc_auth_req;
3633                 evt_data.cfm_req.rmt_auth_req   = p_dev_rec->rmt_auth_req;
3634                 evt_data.cfm_req.loc_io_caps    = btm_cb.devcb.loc_io_caps;
3635                 evt_data.cfm_req.rmt_io_caps    = p_dev_rec->rmt_io_caps;
3636                 break;
3637
3638             case BTM_SP_KEY_NOTIF_EVT:
3639                 /* Passkey notification (other side is a keyboard) */
3640                 STREAM_TO_UINT32 (evt_data.key_notif.passkey, p);
3641
3642                 BTM_TRACE_DEBUG ("BTM_SP_KEY_NOTIF_EVT:  passkey: %u", evt_data.key_notif.passkey);
3643
3644                 btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
3645                 break;
3646
3647 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
3648             case BTM_SP_KEY_REQ_EVT:
3649                 /* HCI_USER_PASSKEY_REQUEST_EVT */
3650                 btm_sec_change_pairing_state (BTM_PAIR_STATE_KEY_ENTRY);
3651                 break;
3652 #endif
3653         }
3654
3655         if (btm_cb.api.p_sp_callback)
3656         {
3657             status = (*btm_cb.api.p_sp_callback) (event, (tBTM_SP_EVT_DATA *)&evt_data);
3658             if (status != BTM_NOT_AUTHORIZED)
3659             {
3660                 return;
3661             }
3662             /* else BTM_NOT_AUTHORIZED means when the app wants to reject the req right now */
3663         }
3664         else if ( (event == BTM_SP_CFM_REQ_EVT) && (evt_data.cfm_req.just_works == TRUE) )
3665         {
3666             /* automatically reply with just works if no sp_cback */
3667             status = BTM_SUCCESS;
3668         }
3669
3670         if (event == BTM_SP_CFM_REQ_EVT)
3671         {
3672             BTM_TRACE_DEBUG ("calling BTM_ConfirmReqReply with status: %d", status);
3673             BTM_ConfirmReqReply (status, p_bda);
3674         }
3675 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
3676         else if (event == BTM_SP_KEY_REQ_EVT)
3677         {
3678             BTM_PasskeyReqReply(status, p_bda, 0);
3679         }
3680 #endif
3681         return;
3682     }
3683
3684     /* Something bad. we can only fail this connection */
3685     btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
3686
3687     if (BTM_SP_CFM_REQ_EVT == event)
3688     {
3689         btsnd_hcic_user_conf_reply (p_bda, FALSE);
3690     }
3691     else if (BTM_SP_KEY_NOTIF_EVT == event)
3692     {
3693         /* do nothing -> it very unlikely to happen.
3694         This event is most likely to be received by a HID host when it first connects to a HID device.
3695         Usually the Host initiated the connection in this case.
3696         On Mobile platforms, if there's a security process happening,
3697         the host probably can not initiate another connection.
3698         BTW (PC) is another story.  */
3699         if (NULL != (p_dev_rec = btm_find_dev (p_bda)) )
3700         {
3701             btm_sec_disconnect (p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE);
3702         }
3703     }
3704 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
3705     else
3706     {
3707         btsnd_hcic_user_passkey_neg_reply(p_bda);
3708     }
3709 #endif
3710 }
3711
3712 /*******************************************************************************
3713 **
3714 ** Function         btm_keypress_notif_evt
3715 **
3716 ** Description      This function is called when a key press notification is
3717 **                  received
3718 **
3719 ** Returns          void
3720 **
3721 *******************************************************************************/
3722 void  btm_keypress_notif_evt (UINT8 *p)
3723 {
3724     tBTM_SP_KEYPRESS    evt_data;
3725     UINT8 *p_bda;
3726
3727     /* parse & report BTM_SP_KEYPRESS_EVT */
3728     if (btm_cb.api.p_sp_callback)
3729     {
3730         p_bda = evt_data.bd_addr;
3731
3732         STREAM_TO_BDADDR (p_bda, p);
3733         evt_data.notif_type = *p;
3734
3735         (*btm_cb.api.p_sp_callback) (BTM_SP_KEYPRESS_EVT, (tBTM_SP_EVT_DATA *)&evt_data);
3736     }
3737 }
3738
3739 /*******************************************************************************
3740 **
3741 ** Function         btm_simple_pair_complete
3742 **
3743 ** Description      This function is called when simple pairing process is
3744 **                  complete
3745 **
3746 ** Returns          void
3747 **
3748 *******************************************************************************/
3749 void btm_simple_pair_complete (UINT8 *p)
3750 {
3751     tBTM_SP_COMPLT  evt_data;
3752     tBTM_SEC_DEV_REC *p_dev_rec;
3753     UINT8           status;
3754     BOOLEAN         disc = FALSE;
3755
3756     status = *p++;
3757     STREAM_TO_BDADDR (evt_data.bd_addr, p);
3758
3759     if ((p_dev_rec = btm_find_dev (evt_data.bd_addr)) == NULL)
3760     {
3761         BTM_TRACE_ERROR ("btm_simple_pair_complete() with unknown BDA: %08x%04x",
3762                           (evt_data.bd_addr[0]<<24) + (evt_data.bd_addr[1]<<16) + (evt_data.bd_addr[2]<<8) + evt_data.bd_addr[3],
3763                           (evt_data.bd_addr[4] << 8) + evt_data.bd_addr[5]);
3764         return;
3765     }
3766
3767     BTM_TRACE_EVENT ("btm_simple_pair_complete()  Pair State: %s  Status:%d  sec_state: %u",
3768                       btm_pair_state_descr(btm_cb.pairing_state),  status, p_dev_rec->sec_state);
3769
3770     evt_data.status = BTM_ERR_PROCESSING;
3771     if (status == HCI_SUCCESS)
3772     {
3773         evt_data.status = BTM_SUCCESS;
3774         p_dev_rec->sec_flags |= BTM_SEC_AUTHENTICATED;
3775     }
3776     else
3777     {
3778         if (status == HCI_ERR_PAIRING_NOT_ALLOWED)
3779         {
3780             /* The test spec wants the peer device to get this failure code. */
3781             btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_DISCONNECT);
3782
3783             /* Change the timer to 1 second */
3784             btu_start_timer (&btm_cb.pairing_tle, BTU_TTYPE_USER_FUNC, BT_1SEC_TIMEOUT);
3785         }
3786         else if (memcmp (btm_cb.pairing_bda, evt_data.bd_addr, BD_ADDR_LEN) == 0)
3787         {
3788             /* stop the timer */
3789             btu_stop_timer (&btm_cb.pairing_tle);
3790
3791             if (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING)
3792             {
3793                 /* the initiating side: will receive auth complete event. disconnect ACL at that time */
3794                 disc = TRUE;
3795             }
3796         }
3797         else
3798             disc = TRUE;
3799     }
3800
3801     /* Let the pairing state stay active, p_auth_complete_callback will report the failure */
3802     memcpy (evt_data.bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN);
3803     memcpy (evt_data.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN);
3804
3805     if (btm_cb.api.p_sp_callback)
3806         (*btm_cb.api.p_sp_callback) (BTM_SP_COMPLT_EVT, (tBTM_SP_EVT_DATA *)&evt_data);
3807
3808     if (disc)
3809     {
3810         /* simple pairing failed */
3811         /* Avoid sending disconnect on HCI_ERR_PEER_USER */
3812         if ((status != HCI_ERR_PEER_USER) && (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST))
3813         {
3814             btm_sec_send_hci_disconnect (p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle);
3815         }
3816     }
3817 }
3818
3819 #if BTM_OOB_INCLUDED == TRUE
3820 /*******************************************************************************
3821 **
3822 ** Function         btm_rem_oob_req
3823 **
3824 ** Description      This function is called to process/report
3825 **                  HCI_REMOTE_OOB_DATA_REQUEST_EVT
3826 **
3827 ** Returns          void
3828 **
3829 *******************************************************************************/
3830 void btm_rem_oob_req (UINT8 *p)
3831 {
3832     UINT8 *p_bda;
3833     tBTM_SP_RMT_OOB  evt_data;
3834     tBTM_SEC_DEV_REC *p_dev_rec;
3835     BT_OCTET16      c;
3836     BT_OCTET16      r;
3837
3838     p_bda = evt_data.bd_addr;
3839
3840     STREAM_TO_BDADDR (p_bda, p);
3841
3842     BTM_TRACE_EVENT ("btm_rem_oob_req() BDA: %02x:%02x:%02x:%02x:%02x:%02x",
3843                       p_bda[0], p_bda[1], p_bda[2], p_bda[3], p_bda[4], p_bda[5]);
3844
3845     if ( (NULL != (p_dev_rec = btm_find_dev (p_bda))) &&
3846          btm_cb.api.p_sp_callback)
3847     {
3848         memcpy (evt_data.bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN);
3849         memcpy (evt_data.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN);
3850         BCM_STRNCPY_S((char *)evt_data.bd_name, sizeof(evt_data.bd_name), (char *)p_dev_rec->sec_bd_name, BTM_MAX_REM_BD_NAME_LEN+1);
3851         evt_data.bd_name[BTM_MAX_REM_BD_NAME_LEN] = 0;
3852
3853         btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP);
3854         if ((*btm_cb.api.p_sp_callback) (BTM_SP_RMT_OOB_EVT, (tBTM_SP_EVT_DATA *)&evt_data) == BTM_NOT_AUTHORIZED)
3855         {
3856             BTM_RemoteOobDataReply(TRUE, p_bda, c, r);
3857         }
3858         return;
3859     }
3860
3861     /* something bad. we can only fail this connection */
3862     btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
3863     btsnd_hcic_rem_oob_neg_reply (p_bda);
3864 }
3865
3866 /*******************************************************************************
3867 **
3868 ** Function         btm_read_local_oob_complete
3869 **
3870 ** Description      This function is called when read local oob data is
3871 **                  completed by the LM
3872 **
3873 ** Returns          void
3874 **
3875 *******************************************************************************/
3876 void btm_read_local_oob_complete (UINT8 *p)
3877 {
3878     tBTM_SP_LOC_OOB evt_data;
3879     UINT8           status = *p++;
3880
3881     BTM_TRACE_EVENT ("btm_read_local_oob_complete:%d", status);
3882     if (status == HCI_SUCCESS)
3883     {
3884         evt_data.status = BTM_SUCCESS;
3885         STREAM_TO_ARRAY16(evt_data.c, p);
3886         STREAM_TO_ARRAY16(evt_data.r, p);
3887     }
3888     else
3889         evt_data.status = BTM_ERR_PROCESSING;
3890
3891     if (btm_cb.api.p_sp_callback)
3892         (*btm_cb.api.p_sp_callback) (BTM_SP_LOC_OOB_EVT, (tBTM_SP_EVT_DATA *)&evt_data);
3893 }
3894 #endif /* BTM_OOB_INCLUDED */
3895
3896 /*******************************************************************************
3897 **
3898 ** Function         btm_sec_auth_collision
3899 **
3900 ** Description      This function is called when authentication or encryption
3901 **                  needs to be retried at a later time.
3902 **
3903 ** Returns          void
3904 **
3905 *******************************************************************************/
3906 static void btm_sec_auth_collision (UINT16 handle)
3907 {
3908     tBTM_SEC_DEV_REC *p_dev_rec;
3909
3910     if (!btm_cb.collision_start_time)
3911         btm_cb.collision_start_time = GKI_get_os_tick_count();
3912
3913     if ((GKI_get_os_tick_count() - btm_cb.collision_start_time) < btm_cb.max_collision_delay)
3914     {
3915         if (handle == BTM_SEC_INVALID_HANDLE)
3916         {
3917             if ((p_dev_rec = btm_sec_find_dev_by_sec_state (BTM_SEC_STATE_AUTHENTICATING)) == NULL)
3918                 p_dev_rec = btm_sec_find_dev_by_sec_state (BTM_SEC_STATE_ENCRYPTING);
3919         }
3920         else
3921             p_dev_rec = btm_find_dev_by_handle (handle);
3922
3923         if (p_dev_rec != NULL)
3924         {
3925             BTM_TRACE_DEBUG ("btm_sec_auth_collision: state %d (retrying in a moment...)", p_dev_rec->sec_state);
3926             /* We will restart authentication after timeout */
3927             if (p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING || p_dev_rec->sec_state == BTM_SEC_STATE_ENCRYPTING)
3928                 p_dev_rec->sec_state = 0;
3929
3930             btm_cb.p_collided_dev_rec = p_dev_rec;
3931             btm_cb.sec_collision_tle.param = (UINT32) btm_sec_collision_timeout;
3932             btu_start_timer (&btm_cb.sec_collision_tle, BTU_TTYPE_USER_FUNC, BT_1SEC_TIMEOUT);
3933         }
3934     }
3935 }
3936
3937 /*******************************************************************************
3938 **
3939 ** Function         btm_sec_auth_complete
3940 **
3941 ** Description      This function is when authentication of the connection is
3942 **                  completed by the LM
3943 **
3944 ** Returns          void
3945 **
3946 *******************************************************************************/
3947 void btm_sec_auth_complete (UINT16 handle, UINT8 status)
3948 {
3949     UINT8            old_sm4;
3950     tBTM_PAIRING_STATE  old_state   = btm_cb.pairing_state;
3951     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev_by_handle (handle);
3952     BOOLEAN             are_bonding = FALSE;
3953
3954     /* Commenting out trace due to obf/compilation problems.
3955     */
3956 #if (BT_USE_TRACES == TRUE)
3957     if (p_dev_rec)
3958     {
3959         BTM_TRACE_EVENT ("Security Manager: auth_complete PairState: %s  handle:%u  status:%d  dev->sec_state: %u  Bda:%08x, RName:%s",
3960                           btm_pair_state_descr (btm_cb.pairing_state),
3961                           handle, status,
3962                           p_dev_rec->sec_state,
3963                           (p_dev_rec->bd_addr[2]<<24)+(p_dev_rec->bd_addr[3]<<16)+(p_dev_rec->bd_addr[4]<<8)+p_dev_rec->bd_addr[5],
3964                           p_dev_rec->sec_bd_name);
3965     }
3966     else
3967     {
3968         BTM_TRACE_EVENT ("Security Manager: auth_complete PairState: %s  handle:%u  status:%d",
3969                           btm_pair_state_descr (btm_cb.pairing_state),
3970                           handle, status);
3971     }
3972 #endif
3973
3974     /* For transaction collision we need to wait and repeat.  There is no need */
3975     /* for random timeout because only slave should receive the result */
3976     if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) || (status == HCI_ERR_DIFF_TRANSACTION_COLLISION))
3977     {
3978         btm_sec_auth_collision(handle);
3979         return;
3980     }
3981     btm_cb.collision_start_time = 0;
3982
3983     btm_restore_mode();
3984
3985     /* Check if connection was made just to do bonding.  If we authenticate
3986        the connection that is up, this is the last event received.
3987     */
3988     if (p_dev_rec
3989         && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
3990         && !(btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE))
3991     {
3992         p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
3993
3994         l2cu_start_post_bond_timer (p_dev_rec->hci_handle);
3995     }
3996
3997     if (!p_dev_rec)
3998         return;
3999
4000     /* keep the old sm4 flag and clear the retry bit in control block */
4001     old_sm4 = p_dev_rec->sm4;
4002     p_dev_rec->sm4 &= ~BTM_SM4_RETRY;
4003
4004     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
4005          &&  (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
4006          &&  (memcmp (p_dev_rec->bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) )
4007         are_bonding = TRUE;
4008
4009     btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4010
4011     if (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING)
4012     {
4013         if ( (btm_cb.api.p_auth_complete_callback && status != HCI_SUCCESS)
4014              &&  (old_state != BTM_PAIR_STATE_IDLE) )
4015         {
4016             (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
4017                                                     p_dev_rec->dev_class,
4018                                                     p_dev_rec->sec_bd_name, status);
4019         }
4020         return;
4021     }
4022
4023     /* There can be a race condition, when we are starting authentication and
4024     ** the peer device is doing encryption.
4025     ** If first we receive encryption change up, then initiated authentication
4026     ** can not be performed.  According to the spec we can not do authentication
4027     ** on the encrypted link, so device is correct.
4028     */
4029     if ((status == HCI_ERR_COMMAND_DISALLOWED)
4030         && ((p_dev_rec->sec_flags & (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED)) ==
4031             (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED)))
4032     {
4033         status = HCI_SUCCESS;
4034     }
4035     /* Currently we do not notify user if it is a keyboard which connects */
4036     /* User probably Disabled the keyboard while it was asleap.  Let her try */
4037     if (btm_cb.api.p_auth_complete_callback)
4038     {
4039         /* report the suthentication status */
4040         if (old_state != BTM_PAIR_STATE_IDLE)
4041             (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
4042                                                     p_dev_rec->dev_class,
4043                                                     p_dev_rec->sec_bd_name, status);
4044     }
4045
4046     p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
4047
4048     /* If this is a bonding procedure can disconnect the link now */
4049     if (are_bonding)
4050     {
4051         p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
4052
4053         if (status != HCI_SUCCESS)
4054         {
4055             if(((status != HCI_ERR_PEER_USER) && (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)))
4056                 btm_sec_send_hci_disconnect (p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle);
4057         }
4058         else
4059         {
4060             BTM_TRACE_DEBUG ("TRYING TO DECIDE IF CAN USE SMP_BR_CHNL");
4061             if (p_dev_rec->new_encryption_key_is_p256 && (btm_sec_use_smp_br_chnl(p_dev_rec)))
4062             {
4063                 BTM_TRACE_DEBUG ("link encrypted afer dedic bonding can use SMP_BR_CHNL");
4064
4065                 if (btm_sec_is_master(p_dev_rec))
4066                 {
4067                     // Encryption is required to start SM over BR/EDR.
4068                     // Indicate that this is encryption after authentication.
4069                     BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL);
4070                 }
4071             }
4072
4073             l2cu_start_post_bond_timer (p_dev_rec->hci_handle);
4074         }
4075         return;
4076     }
4077
4078     /* If authentication failed, notify the waiting layer */
4079     if (status != HCI_SUCCESS)
4080     {
4081         if ((old_sm4 & BTM_SM4_RETRY) == 0)
4082         {
4083             /* allow retry only once */
4084             if (status == HCI_ERR_LMP_ERR_TRANS_COLLISION)
4085             {
4086                 /* not retried yet. set the retry bit */
4087                 p_dev_rec->sm4 |= BTM_SM4_RETRY;
4088                 BTM_TRACE_DEBUG ("Collision retry sm4:x%x sec_flags:0x%x", p_dev_rec->sm4, p_dev_rec->sec_flags);
4089             }
4090             /* this retry for missing key is for Lisbon or later only.
4091              * Legacy device do not need this. the controller will drive the retry automatically */
4092             else if (HCI_ERR_KEY_MISSING == status && BTM_SEC_IS_SM4(p_dev_rec->sm4))
4093             {
4094                 /* not retried yet. set the retry bit */
4095                 p_dev_rec->sm4 |= BTM_SM4_RETRY;
4096                 p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
4097                 BTM_TRACE_DEBUG ("Retry for missing key sm4:x%x sec_flags:0x%x", p_dev_rec->sm4, p_dev_rec->sec_flags);
4098
4099                 /* With BRCM controller, we do not need to delete the stored link key in controller.
4100                 If the stack may sit on top of other controller, we may need this
4101                 BTM_DeleteStoredLinkKey (bd_addr, NULL); */
4102             }
4103
4104             if (p_dev_rec->sm4 & BTM_SM4_RETRY)
4105             {
4106                 btm_sec_execute_procedure (p_dev_rec);
4107                 return;
4108             }
4109         }
4110
4111         btm_sec_dev_rec_cback_event (p_dev_rec, BTM_ERR_PROCESSING, FALSE);
4112
4113         if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)
4114         {
4115             btm_sec_send_hci_disconnect (p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle);
4116         }
4117         return;
4118     }
4119
4120     p_dev_rec->sec_flags |= BTM_SEC_AUTHENTICATED;
4121
4122     /* Authentication succeeded, execute the next security procedure, if any */
4123     status = btm_sec_execute_procedure (p_dev_rec);
4124
4125     /* If there is no next procedure, or procedure failed to start, notify the caller */
4126     if (status != BTM_CMD_STARTED)
4127         btm_sec_dev_rec_cback_event (p_dev_rec, status, FALSE);
4128 }
4129
4130 /*******************************************************************************
4131 **
4132 ** Function         btm_sec_encrypt_change
4133 **
4134 ** Description      This function is when encryption of the connection is
4135 **                  completed by the LM
4136 **
4137 ** Returns          void
4138 **
4139 *******************************************************************************/
4140 void btm_sec_encrypt_change (UINT16 handle, UINT8 status, UINT8 encr_enable)
4141 {
4142     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev_by_handle (handle);
4143 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
4144     tACL_CONN       *p_acl = NULL;
4145     UINT8           acl_idx = btm_handle_to_acl_index(handle);
4146 #endif
4147     BTM_TRACE_EVENT ("Security Manager: encrypt_change status:%d State:%d, encr_enable = %d",
4148                       status, (p_dev_rec) ? p_dev_rec->sec_state : 0, encr_enable);
4149     BTM_TRACE_DEBUG ("before update p_dev_rec->sec_flags=0x%x", (p_dev_rec) ? p_dev_rec->sec_flags : 0 );
4150
4151     /* For transaction collision we need to wait and repeat.  There is no need */
4152     /* for random timeout because only slave should receive the result */
4153     if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) || (status == HCI_ERR_DIFF_TRANSACTION_COLLISION))
4154     {
4155         btm_sec_auth_collision(handle);
4156         return;
4157     }
4158     btm_cb.collision_start_time = 0;
4159
4160     if (!p_dev_rec)
4161         return;
4162
4163     if ((status == HCI_SUCCESS) && encr_enable)
4164     {
4165         if (p_dev_rec->hci_handle == handle)
4166             p_dev_rec->sec_flags |= (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED);
4167         else
4168             p_dev_rec->sec_flags |= (BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED);
4169     }
4170
4171     /* It is possible that we decrypted the link to perform role switch */
4172     /* mark link not to be encrypted, so that when we execute security next time it will kick in again */
4173     if ((status == HCI_SUCCESS) && !encr_enable)
4174     {
4175         if (p_dev_rec->hci_handle == handle)
4176             p_dev_rec->sec_flags &= ~BTM_SEC_ENCRYPTED;
4177         else
4178             p_dev_rec->sec_flags &= ~BTM_SEC_LE_ENCRYPTED;
4179     }
4180
4181     BTM_TRACE_DEBUG ("after update p_dev_rec->sec_flags=0x%x", p_dev_rec->sec_flags );
4182
4183 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
4184     if (acl_idx != MAX_L2CAP_LINKS )
4185         p_acl = &btm_cb.acl_db[acl_idx];
4186
4187     btm_sec_check_pending_enc_req (p_dev_rec, p_acl->transport, encr_enable);
4188
4189     if (p_acl && p_acl->transport == BT_TRANSPORT_LE)
4190     {
4191         if (status == HCI_ERR_KEY_MISSING ||
4192             status == HCI_ERR_AUTH_FAILURE ||
4193             status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE)
4194         {
4195             p_dev_rec->sec_flags &= ~ (BTM_SEC_LE_LINK_KEY_KNOWN);
4196             p_dev_rec->ble.key_type = BTM_LE_KEY_NONE;
4197         }
4198         btm_ble_link_encrypted(p_dev_rec->bd_addr, encr_enable);
4199         return;
4200     }
4201     else
4202         /* BR/EDR connection, update the encryption key size to be 16 as always */
4203         p_dev_rec->enc_key_size = 16;
4204
4205     BTM_TRACE_DEBUG ("in btm_sec_encrypt_change new_encr_key_256 is %d",
4206                        p_dev_rec->new_encryption_key_is_p256);
4207
4208     if ((status == HCI_SUCCESS) && encr_enable && (p_dev_rec->hci_handle == handle))
4209     {
4210         if (p_dev_rec->new_encryption_key_is_p256)
4211         {
4212             if (btm_sec_use_smp_br_chnl(p_dev_rec) &&
4213                 btm_sec_is_master(p_dev_rec))
4214             {
4215                 /* BR/EDR is encrypted with LK that can be used to derive LE LTK */
4216                 p_dev_rec->new_encryption_key_is_p256 = FALSE;
4217
4218                 BTM_TRACE_DEBUG ("btm_sec_encrypt_change start SM over BR/EDR");
4219                 SMP_BR_PairWith(p_dev_rec->bd_addr);
4220             }
4221         }
4222         else
4223         {   /* BR/EDR is successfully encrypted. Correct LK type if needed
4224               (BR/EDR LK derived from LE LTK was used for encryption) */
4225             if ((encr_enable == 1)  && /* encryption is ON for SSP */
4226                 /* LK type is for BR/EDR SC */
4227                 (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256 ||
4228                  p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256))
4229             {
4230                 if (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256)
4231                     p_dev_rec->link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB;
4232                 else /* BTM_LKEY_TYPE_AUTH_COMB_P_256 */
4233                     p_dev_rec->link_key_type = BTM_LKEY_TYPE_AUTH_COMB;
4234
4235                 BTM_TRACE_DEBUG("updated link key type to %d", p_dev_rec->link_key_type);
4236                 btm_send_link_key_notif(p_dev_rec);
4237             }
4238         }
4239     }
4240 #else
4241     btm_sec_check_pending_enc_req (p_dev_rec, BT_TRANSPORT_BR_EDR, encr_enable);
4242 #endif /* BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE */
4243
4244     /* If this encryption was started by peer do not need to do anything */
4245     if (p_dev_rec->sec_state != BTM_SEC_STATE_ENCRYPTING)
4246     {
4247         if (BTM_SEC_STATE_DELAY_FOR_ENC == p_dev_rec->sec_state)
4248         {
4249             p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
4250             p_dev_rec->p_callback = NULL;
4251             l2cu_resubmit_pending_sec_req (p_dev_rec->bd_addr);
4252         }
4253         return;
4254     }
4255
4256     p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
4257
4258     /* If encryption setup failed, notify the waiting layer */
4259     if (status != HCI_SUCCESS)
4260     {
4261         btm_sec_dev_rec_cback_event (p_dev_rec, BTM_ERR_PROCESSING, FALSE);
4262         return;
4263     }
4264
4265     /* Encryption setup succeeded, execute the next security procedure, if any */
4266     status = (UINT8)btm_sec_execute_procedure (p_dev_rec);
4267
4268     /* If there is no next procedure, or procedure failed to start, notify the caller */
4269     if (status != BTM_CMD_STARTED)
4270         btm_sec_dev_rec_cback_event (p_dev_rec, status, FALSE);
4271 }
4272
4273 /*******************************************************************************
4274 **
4275 ** Function         btm_sec_connect_after_reject_timeout
4276 **
4277 ** Description      Connection for bonding could not start because of the collision
4278 **                  Initiate outgoing connection
4279 **
4280 ** Returns          Pointer to the TLE struct
4281 **
4282 *******************************************************************************/
4283 static void btm_sec_connect_after_reject_timeout (TIMER_LIST_ENT *p_tle)
4284 {
4285     tBTM_SEC_DEV_REC *p_dev_rec = btm_cb.p_collided_dev_rec;
4286     UNUSED(p_tle);
4287
4288     BTM_TRACE_EVENT ("btm_sec_connect_after_reject_timeout()");
4289     btm_cb.sec_collision_tle.param = 0;
4290     btm_cb.p_collided_dev_rec = 0;
4291
4292     if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED)
4293     {
4294         BTM_TRACE_WARNING ("Security Manager: btm_sec_connect_after_reject_timeout: failed to start connection");
4295
4296         btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4297
4298         if (btm_cb.api.p_auth_complete_callback)
4299         (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,  p_dev_rec->dev_class,
4300                                                 p_dev_rec->sec_bd_name, HCI_ERR_MEMORY_FULL);
4301     }
4302 }
4303
4304 /*******************************************************************************
4305 **
4306 ** Function         btm_sec_connected
4307 **
4308 ** Description      This function is when a connection to the peer device is
4309 **                  establsihed
4310 **
4311 ** Returns          void
4312 **
4313 *******************************************************************************/
4314 void btm_sec_connected (UINT8 *bda, UINT16 handle, UINT8 status, UINT8 enc_mode)
4315 {
4316     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bda);
4317     UINT8            res;
4318     BOOLEAN          is_pairing_device = FALSE;
4319     tACL_CONN        *p_acl_cb;
4320     UINT8            bit_shift = 0;
4321
4322     btm_acl_resubmit_page();
4323
4324     /* Commenting out trace due to obf/compilation problems.
4325     */
4326 #if (BT_USE_TRACES == TRUE)
4327     if (p_dev_rec)
4328     {
4329         BTM_TRACE_EVENT ("Security Manager: btm_sec_connected in state: %s  handle:%d status:%d enc_mode:%d  bda:%x RName:%s",
4330                           btm_pair_state_descr(btm_cb.pairing_state), handle, status, enc_mode,
4331                           (bda[2]<<24)+(bda[3]<<16)+(bda[4]<<8)+bda[5],
4332                           p_dev_rec->sec_bd_name);
4333     }
4334     else
4335     {
4336         BTM_TRACE_EVENT ("Security Manager: btm_sec_connected in state: %s  handle:%d status:%d enc_mode:%d  bda:%x ",
4337                           btm_pair_state_descr(btm_cb.pairing_state), handle, status, enc_mode,
4338                           (bda[2]<<24)+(bda[3]<<16)+(bda[4]<<8)+bda[5]);
4339     }
4340 #endif
4341
4342     if (!p_dev_rec)
4343     {
4344         /* There is no device record for new connection.  Allocate one */
4345         if (status == HCI_SUCCESS)
4346         {
4347             p_dev_rec = btm_sec_alloc_dev (bda);
4348         }
4349         else
4350         {
4351             /* can not find the device record and the status is error,
4352              * just ignore it */
4353             return;
4354         }
4355     }
4356     else    /* Update the timestamp for this device */
4357     {
4358
4359 #if BLE_INCLUDED == TRUE
4360         bit_shift = (handle == p_dev_rec->ble_hci_handle) ? 8 :0;
4361 #endif
4362         p_dev_rec->timestamp = btm_cb.dev_rec_count++;
4363         if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND)
4364         {
4365             /* tell L2CAP it's a bonding connection. */
4366             if ( (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
4367                  &&  (memcmp (btm_cb.pairing_bda, p_dev_rec->bd_addr, BD_ADDR_LEN) == 0)
4368                  &&  (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) )
4369             {
4370                 /* if incoming connection failed while pairing, then try to connect and continue */
4371                 /* Motorola S9 disconnects without asking pin code */
4372                 if ((status != HCI_SUCCESS)&&(btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ))
4373                 {
4374                     BTM_TRACE_WARNING ("Security Manager: btm_sec_connected: incoming connection failed without asking PIN");
4375
4376                     p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND;
4377                     if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
4378                     {
4379                         /* Start timer with 0 to initiate connection with new LCB */
4380                         /* because L2CAP will delete current LCB with this event  */
4381                         btm_cb.p_collided_dev_rec = p_dev_rec;
4382                         btm_cb.sec_collision_tle.param = (UINT32) btm_sec_connect_after_reject_timeout;
4383                         btu_start_timer (&btm_cb.sec_collision_tle, BTU_TTYPE_USER_FUNC, 0);
4384                     }
4385                     else
4386                     {
4387                         btm_sec_change_pairing_state (BTM_PAIR_STATE_GET_REM_NAME);
4388                         BTM_ReadRemoteDeviceName(p_dev_rec->bd_addr, NULL, BT_TRANSPORT_BR_EDR);
4389                     }
4390 #if BTM_DISC_DURING_RS == TRUE
4391                     p_dev_rec->rs_disc_pending   = BTM_SEC_RS_NOT_PENDING;     /* reset flag */
4392 #endif
4393                     return;
4394                 }
4395                 else
4396                 {
4397                     l2cu_update_lcb_4_bonding(p_dev_rec->bd_addr, TRUE);
4398                 }
4399             }
4400             /* always clear the pending flag */
4401             p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND;
4402         }
4403     }
4404
4405 #if BLE_INCLUDED == TRUE
4406     p_dev_rec->device_type |= BT_DEVICE_TYPE_BREDR;
4407 #endif
4408
4409 #if BTM_DISC_DURING_RS == TRUE
4410     p_dev_rec->rs_disc_pending   = BTM_SEC_RS_NOT_PENDING;     /* reset flag */
4411 #endif
4412
4413     p_dev_rec->rs_disc_pending   = BTM_SEC_RS_NOT_PENDING;     /* reset flag */
4414
4415     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
4416          && (memcmp (btm_cb.pairing_bda, bda, BD_ADDR_LEN) == 0) )
4417     {
4418         /* if we rejected incoming connection from bonding device */
4419         if ((status == HCI_ERR_HOST_REJECT_DEVICE)
4420             &&(btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT))
4421         {
4422             BTM_TRACE_WARNING ("Security Manager: btm_sec_connected: HCI_Conn_Comp Flags:0x%04x, sm4: 0x%x",
4423                 btm_cb.pairing_flags, p_dev_rec->sm4);
4424
4425             btm_cb.pairing_flags &= ~BTM_PAIR_FLAGS_REJECTED_CONNECT;
4426             if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4))
4427             {
4428                 /* Try again: RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */
4429                 btm_sec_change_pairing_state (BTM_PAIR_STATE_GET_REM_NAME);
4430                 BTM_ReadRemoteDeviceName(bda, NULL, BT_TRANSPORT_BR_EDR);
4431                 return;
4432             }
4433
4434             /* if we already have pin code */
4435             if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN)
4436             {
4437                 /* Start timer with 0 to initiate connection with new LCB */
4438                 /* because L2CAP will delete current LCB with this event  */
4439                 btm_cb.p_collided_dev_rec = p_dev_rec;
4440                 btm_cb.sec_collision_tle.param = (UINT32) btm_sec_connect_after_reject_timeout;
4441                 btu_start_timer (&btm_cb.sec_collision_tle, BTU_TTYPE_USER_FUNC, 0);
4442             }
4443
4444             return;
4445         }
4446         /* wait for incoming connection without resetting pairing state */
4447         else if (status == HCI_ERR_CONNECTION_EXISTS)
4448         {
4449             BTM_TRACE_WARNING ("Security Manager: btm_sec_connected: Wait for incoming connection");
4450             return;
4451         }
4452
4453         is_pairing_device = TRUE;
4454     }
4455
4456     /* If connection was made to do bonding restore link security if changed */
4457     btm_restore_mode();
4458
4459     /* if connection fails during pin request, notify application */
4460     if (status != HCI_SUCCESS)
4461     {
4462         /* If connection failed because of during pairing, need to tell user */
4463         if (is_pairing_device)
4464         {
4465             p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
4466             p_dev_rec->sec_flags &= ~((BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED) << bit_shift);
4467             BTM_TRACE_DEBUG ("security_required:%x ", p_dev_rec->security_required );
4468
4469             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4470
4471             /* We need to notify host that the key is not known any more */
4472             if (btm_cb.api.p_auth_complete_callback)
4473             {
4474                 (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
4475                                                         p_dev_rec->dev_class,
4476                                                         p_dev_rec->sec_bd_name, status);
4477             }
4478         }
4479  /*
4480      Do not send authentication failure, if following conditions hold good
4481       1.  BTM Sec Pairing state is idle
4482       2.  Link key for the remote device is present.
4483       3.  Remote is SSP capable.
4484   */
4485         else if  ((p_dev_rec->link_key_type  <= BTM_LKEY_TYPE_REMOTE_UNIT) &&
4486                  (((status == HCI_ERR_AUTH_FAILURE)                      ||
4487                  (status == HCI_ERR_KEY_MISSING)                         ||
4488                  (status == HCI_ERR_HOST_REJECT_SECURITY)                ||
4489                  (status == HCI_ERR_PAIRING_NOT_ALLOWED)                 ||
4490                  (status == HCI_ERR_UNIT_KEY_USED)                       ||
4491                  (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) ||
4492                  (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE)           ||
4493                  (status == HCI_ERR_REPEATED_ATTEMPTS))))
4494         {
4495             p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
4496             p_dev_rec->sec_flags &= ~ (BTM_SEC_LE_LINK_KEY_KNOWN << bit_shift);
4497
4498
4499 #ifdef BRCM_NOT_4_BTE
4500             /* If we rejected pairing, pass this special result code */
4501             if (btm_cb.acl_disc_reason == HCI_ERR_HOST_REJECT_SECURITY)
4502             {
4503                 status = HCI_ERR_HOST_REJECT_SECURITY;
4504             }
4505 #endif
4506
4507             /* We need to notify host that the key is not known any more */
4508             if (btm_cb.api.p_auth_complete_callback)
4509             {
4510                 (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
4511                                                         p_dev_rec->dev_class,
4512                                                         p_dev_rec->sec_bd_name, status);
4513             }
4514         }
4515
4516         if (status == HCI_ERR_CONNECTION_TOUT || status == HCI_ERR_LMP_RESPONSE_TIMEOUT  ||
4517             status == HCI_ERR_UNSPECIFIED     || status == HCI_ERR_PAGE_TIMEOUT)
4518             btm_sec_dev_rec_cback_event (p_dev_rec, BTM_DEVICE_TIMEOUT, FALSE);
4519         else
4520             btm_sec_dev_rec_cback_event (p_dev_rec, BTM_ERR_PROCESSING, FALSE);
4521
4522         return;
4523     }
4524
4525     /* If initiated dedicated bonding, return the link key now, and initiate disconnect */
4526     /* If dedicated bonding, and we now have a link key, we are all done */
4527     if ( is_pairing_device
4528          && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) )
4529     {
4530         if (p_dev_rec->link_key_not_sent)
4531         {
4532             p_dev_rec->link_key_not_sent = FALSE;
4533             btm_send_link_key_notif(p_dev_rec);
4534         }
4535
4536         p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
4537
4538         /* remember flag before it is initialized */
4539         if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
4540             res = TRUE;
4541         else
4542             res = FALSE;
4543
4544         if (btm_cb.api.p_auth_complete_callback)
4545             (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
4546                                                     p_dev_rec->dev_class,
4547                                                     p_dev_rec->sec_bd_name, HCI_SUCCESS);
4548
4549         btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4550
4551         if ( res )
4552         {
4553             /* Let l2cap start bond timer */
4554             l2cu_update_lcb_4_bonding (p_dev_rec->bd_addr, TRUE);
4555         }
4556
4557         return;
4558     }
4559
4560     p_dev_rec->hci_handle = handle;
4561
4562     /* role may not be correct here, it will be updated by l2cap, but we need to */
4563     /* notify btm_acl that link is up, so starting of rmt name request will not */
4564     /* set paging flag up */
4565     p_acl_cb = btm_bda_to_acl(bda, BT_TRANSPORT_BR_EDR);
4566     if (p_acl_cb)
4567     {
4568         /* whatever is in btm_establish_continue() without reporting the BTM_BL_CONN_EVT event */
4569 #if (!defined(BTM_BYPASS_EXTRA_ACL_SETUP) || BTM_BYPASS_EXTRA_ACL_SETUP == FALSE)
4570         /* For now there are a some devices that do not like sending */
4571         /* commands events and data at the same time. */
4572         /* Set the packet types to the default allowed by the device */
4573         btm_set_packet_types (p_acl_cb, btm_cb.btm_acl_pkt_types_supported);
4574
4575         if (btm_cb.btm_def_link_policy)
4576             BTM_SetLinkPolicy (p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy);
4577 #endif
4578     }
4579     btm_acl_created (bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, handle, HCI_ROLE_SLAVE, BT_TRANSPORT_BR_EDR);
4580
4581     /* Initialize security flags.  We need to do that because some            */
4582     /* authorization complete could have come after the connection is dropped */
4583     /* and that would set wrong flag that link has been authorized already    */
4584     p_dev_rec->sec_flags &= ~((BTM_SEC_AUTHORIZED | BTM_SEC_AUTHENTICATED |
4585                               BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED) << bit_shift);
4586
4587     if (enc_mode != HCI_ENCRYPT_MODE_DISABLED)
4588         p_dev_rec->sec_flags |= ((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED) << bit_shift);
4589
4590     if (btm_cb.security_mode == BTM_SEC_MODE_LINK)
4591         p_dev_rec->sec_flags |= (BTM_SEC_AUTHENTICATED << bit_shift);
4592
4593     p_dev_rec->link_key_changed = FALSE;
4594
4595     /* After connection is established we perform security if we do not know */
4596     /* the name, or if we are originator because some procedure can have */
4597     /* been scheduled while connection was down */
4598     BTM_TRACE_DEBUG ("is_originator:%d ", p_dev_rec->is_originator);
4599     if (!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) || p_dev_rec->is_originator)
4600     {
4601         if ((res = btm_sec_execute_procedure (p_dev_rec)) != BTM_CMD_STARTED)
4602             btm_sec_dev_rec_cback_event (p_dev_rec, res, FALSE);
4603     }
4604     return;
4605 }
4606
4607 /*******************************************************************************
4608 **
4609 ** Function         btm_sec_disconnect
4610 **
4611 ** Description      This function is called to disconnect HCI link
4612 **
4613 ** Returns          btm status
4614 **
4615 *******************************************************************************/
4616 tBTM_STATUS btm_sec_disconnect (UINT16 handle, UINT8 reason)
4617 {
4618     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev_by_handle (handle);
4619
4620     /* In some weird race condition we may not have a record */
4621     if (!p_dev_rec)
4622     {
4623         btsnd_hcic_disconnect (handle, reason);
4624         return(BTM_SUCCESS);
4625     }
4626
4627     /* If we are in the process of bonding we need to tell client that auth failed */
4628     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
4629          &&  (memcmp (btm_cb.pairing_bda, p_dev_rec->bd_addr, BD_ADDR_LEN) == 0)
4630          &&  (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) )
4631     {
4632         /* we are currently doing bonding.  Link will be disconnected when done */
4633         btm_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE;
4634         return(BTM_BUSY);
4635     }
4636
4637     return(btm_sec_send_hci_disconnect(p_dev_rec, reason, handle));
4638 }
4639
4640 /*******************************************************************************
4641 **
4642 ** Function         btm_sec_disconnected
4643 **
4644 ** Description      This function is when a connection to the peer device is
4645 **                  dropped
4646 **
4647 ** Returns          void
4648 **
4649 *******************************************************************************/
4650 void btm_sec_disconnected (UINT16 handle, UINT8 reason)
4651 {
4652     tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev_by_handle (handle);
4653     UINT8             old_pairing_flags = btm_cb.pairing_flags;
4654     int               result = HCI_ERR_AUTH_FAILURE;
4655     tBTM_SEC_CALLBACK   *p_callback = NULL;
4656     tBT_TRANSPORT      transport = BT_TRANSPORT_BR_EDR;
4657
4658     /* If page was delayed for disc complete, can do it now */
4659     btm_cb.discing = FALSE;
4660
4661     btm_acl_resubmit_page();
4662
4663     if (!p_dev_rec)
4664         return;
4665
4666     transport  = (handle == p_dev_rec->hci_handle) ? BT_TRANSPORT_BR_EDR: BT_TRANSPORT_LE;
4667
4668     p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING;     /* reset flag */
4669
4670 #if BTM_DISC_DURING_RS == TRUE
4671     LOG_INFO("%s clearing pending flag handle:%d reason:%d", __func__, handle, reason);
4672     p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING;     /* reset flag */
4673 #endif
4674
4675     /* clear unused flags */
4676     p_dev_rec->sm4 &= BTM_SM4_TRUE;
4677
4678     uint8_t *bd_addr = (uint8_t *)p_dev_rec->bd_addr;
4679     BTM_TRACE_EVENT("%s sec_req:x%x state:%s reason:%d bd_addr:%02x:%02x:%02x:%02x:%02x:%02x"
4680             "  remote_name:%s", __func__, p_dev_rec->security_required, btm_pair_state_descr(btm_cb.pairing_state),
4681             reason, bd_addr[0], bd_addr[1], bd_addr[2], bd_addr[3], bd_addr[4], bd_addr[5], p_dev_rec->sec_bd_name);
4682
4683     BTM_TRACE_EVENT("%s before update sec_flags=0x%x", __func__, p_dev_rec->sec_flags);
4684
4685     /* If we are in the process of bonding we need to tell client that auth failed */
4686     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
4687          && (memcmp (btm_cb.pairing_bda, p_dev_rec->bd_addr, BD_ADDR_LEN) == 0))
4688     {
4689         btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4690         p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
4691         if (btm_cb.api.p_auth_complete_callback)
4692         {
4693             /* If the disconnection reason is REPEATED_ATTEMPTS,
4694                send this error message to complete callback function
4695                to display the error message of Repeated attempts.
4696                All others, send HCI_ERR_AUTH_FAILURE. */
4697             if (reason == HCI_ERR_REPEATED_ATTEMPTS)
4698             {
4699                 result = HCI_ERR_REPEATED_ATTEMPTS;
4700             }
4701             else if (old_pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
4702             {
4703                 result = HCI_ERR_HOST_REJECT_SECURITY;
4704             }
4705             (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,     p_dev_rec->dev_class,
4706                                                     p_dev_rec->sec_bd_name, result);
4707         }
4708     }
4709
4710 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
4711     p_dev_rec->enc_key_size = 0;
4712     btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, p_dev_rec->bd_addr, HCI_SUCCESS);
4713     /* see sec_flags processing in btm_acl_removed */
4714
4715     if (transport == BT_TRANSPORT_LE)
4716     {
4717         p_dev_rec->ble_hci_handle = BTM_SEC_INVALID_HANDLE;
4718         p_dev_rec->sec_flags &= ~(BTM_SEC_LE_AUTHENTICATED|BTM_SEC_LE_ENCRYPTED);
4719     }
4720     else
4721 #endif
4722     {
4723         p_dev_rec->hci_handle = BTM_SEC_INVALID_HANDLE;
4724         p_dev_rec->sec_flags &= ~(BTM_SEC_AUTHORIZED | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED);
4725     }
4726
4727 #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
4728     if (p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH)
4729     {
4730         p_dev_rec->sec_state = (transport == BT_TRANSPORT_LE) ?
4731                                 BTM_SEC_STATE_DISCONNECTING : BTM_SEC_STATE_DISCONNECTING_BLE;
4732         return;
4733     }
4734 #endif
4735     p_dev_rec->sec_state  = BTM_SEC_STATE_IDLE;
4736     p_dev_rec->security_required = BTM_SEC_NONE;
4737
4738     p_callback = p_dev_rec->p_callback;
4739
4740     /* if security is pending, send callback to clean up the security state */
4741     if(p_callback)
4742     {
4743         p_dev_rec->p_callback = NULL; /* when the peer device time out the authentication before
4744                                          we do, this call back must be reset here */
4745         (*p_callback) (p_dev_rec->bd_addr, transport, p_dev_rec->p_ref_data, BTM_ERR_PROCESSING);
4746     }
4747
4748     BTM_TRACE_EVENT("%s after update sec_flags=0x%x", __func__, p_dev_rec->sec_flags);
4749 }
4750
4751 /*******************************************************************************
4752 **
4753 ** Function         btm_sec_link_key_notification
4754 **
4755 ** Description      This function is called when a new connection link key is
4756 **                  generated
4757 **
4758 ** Returns          Pointer to the record or NULL
4759 **
4760 *******************************************************************************/
4761 void btm_sec_link_key_notification (UINT8 *p_bda, UINT8 *p_link_key, UINT8 key_type)
4762 {
4763     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_or_alloc_dev (p_bda);
4764     BOOLEAN         we_are_bonding = FALSE;
4765     BOOLEAN         ltk_derived_lk  = FALSE;
4766
4767     BTM_TRACE_EVENT ("btm_sec_link_key_notification()  BDA:%04x%08x, TYPE: %d",
4768                       (p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5],
4769                       key_type);
4770
4771     if ((key_type >= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_COMBINATION) &&
4772         (key_type <= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_AUTH_COMB_P_256))
4773     {
4774         ltk_derived_lk = TRUE;
4775         key_type -= BTM_LTK_DERIVED_LKEY_OFFSET;
4776     }
4777     /* If connection was made to do bonding restore link security if changed */
4778     btm_restore_mode();
4779
4780     if (key_type != BTM_LKEY_TYPE_CHANGED_COMB)
4781         p_dev_rec->link_key_type = key_type;
4782
4783     p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_KNOWN;
4784 #if (BLE_INCLUDED == TRUE)
4785     /* BR/EDR connection, update the encryption key size to be 16 as always */
4786     p_dev_rec->enc_key_size = 16;
4787 #endif
4788     memcpy (p_dev_rec->link_key, p_link_key, LINK_KEY_LEN);
4789
4790     if ( (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
4791          && (memcmp (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN) == 0) )
4792     {
4793         if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
4794             we_are_bonding = TRUE;
4795         else
4796             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4797     }
4798
4799     /* save LTK derived LK no matter what */
4800     if (ltk_derived_lk)
4801     {
4802         if (btm_cb.api.p_link_key_callback)
4803         {
4804                 BTM_TRACE_DEBUG ("%s() Save LTK derived LK (key_type = %d)",
4805                                   __FUNCTION__, p_dev_rec->link_key_type);
4806                 (*btm_cb.api.p_link_key_callback) (p_bda, p_dev_rec->dev_class,
4807                                                    p_dev_rec->sec_bd_name,
4808                                                    p_link_key, p_dev_rec->link_key_type);
4809         }
4810     }
4811 #if BTM_CROSS_TRANSP_KEY_DERIVATION == TRUE
4812     else
4813     {
4814         if ((p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256) ||
4815             (p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256))
4816         {
4817              p_dev_rec->new_encr_key_256 = TRUE;
4818              BTM_TRACE_DEBUG ("%s set new_encr_key_256 to %d",
4819                                __func__, p_dev_rec->new_encr_key_256);
4820         }
4821     }
4822 #endif
4823
4824     /* If name is not known at this point delay calling callback until the name is   */
4825     /* resolved. Unless it is a HID Device and we really need to send all link keys. */
4826     if ((!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
4827         &&  ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) != BTM_COD_MAJOR_PERIPHERAL)) )
4828     {
4829         BTM_TRACE_EVENT ("btm_sec_link_key_notification()  Delayed BDA: %08x%04x Type:%d",
4830                           (p_bda[0]<<24) + (p_bda[1]<<16) + (p_bda[2]<<8) + p_bda[3],
4831                           (p_bda[4] << 8) + p_bda[5], key_type);
4832
4833         p_dev_rec->link_key_not_sent = TRUE;
4834
4835         /* If it is for bonding nothing else will follow, so we need to start name resolution */
4836         if (we_are_bonding)
4837         {
4838             if (!(btsnd_hcic_rmt_name_req (p_bda, HCI_PAGE_SCAN_REP_MODE_R1, HCI_MANDATARY_PAGE_SCAN_MODE, 0)))
4839                 btm_inq_rmt_name_failed();
4840         }
4841
4842         BTM_TRACE_EVENT ("rmt_io_caps:%d, sec_flags:x%x, dev_class[1]:x%02x", p_dev_rec->rmt_io_caps, p_dev_rec->sec_flags, p_dev_rec->dev_class[1])
4843         return;
4844     }
4845
4846     /* If its not us who perform authentication, we should tell stackserver */
4847     /* that some authentication has been completed                          */
4848     /* This is required when different entities receive link notification and auth complete */
4849     if (!(p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE))
4850     {
4851         if (btm_cb.api.p_auth_complete_callback)
4852             (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class,
4853                                                     p_dev_rec->sec_bd_name, HCI_SUCCESS);
4854     }
4855
4856     /* We will save link key only if the user authorized it - BTE report link key in all cases */
4857 #ifdef BRCM_NONE_BTE
4858     if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED)
4859 #endif
4860     {
4861         if (btm_cb.api.p_link_key_callback)
4862         {
4863             (*btm_cb.api.p_link_key_callback) (p_bda, p_dev_rec->dev_class,  p_dev_rec->sec_bd_name,
4864                                                p_link_key, p_dev_rec->link_key_type);
4865         }
4866     }
4867 }
4868
4869 /*******************************************************************************
4870 **
4871 ** Function         btm_sec_link_key_request
4872 **
4873 ** Description      This function is called when controller requests link key
4874 **
4875 ** Returns          Pointer to the record or NULL
4876 **
4877 *******************************************************************************/
4878 void btm_sec_link_key_request (UINT8 *p_bda)
4879 {
4880     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_or_alloc_dev (p_bda);
4881
4882     BTM_TRACE_EVENT ("btm_sec_link_key_request()  BDA: %02x:%02x:%02x:%02x:%02x:%02x",
4883                       p_bda[0], p_bda[1], p_bda[2], p_bda[3], p_bda[4], p_bda[5]);
4884
4885     if( (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ) &&
4886         (btm_cb.collision_start_time != 0) &&
4887         (memcmp (btm_cb.p_collided_dev_rec->bd_addr, p_bda, BD_ADDR_LEN) == 0) )
4888     {
4889         BTM_TRACE_EVENT ("btm_sec_link_key_request() rejecting link key req "
4890             "State: %d START_TIMEOUT : %d",
4891              btm_cb.pairing_state, btm_cb.collision_start_time);
4892         btsnd_hcic_link_key_neg_reply (p_bda);
4893         return;
4894     }
4895     if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)
4896     {
4897         btsnd_hcic_link_key_req_reply (p_bda, p_dev_rec->link_key);
4898         return;
4899     }
4900
4901     /* Notify L2CAP to increase timeout */
4902     l2c_pin_code_request (p_bda);
4903
4904     /* The link key is not in the database and it is not known to the manager */
4905     btsnd_hcic_link_key_neg_reply (p_bda);
4906 }
4907
4908 /*******************************************************************************
4909 **
4910 ** Function         btm_sec_pairing_timeout
4911 **
4912 ** Description      This function is called when host does not provide PIN
4913 **                  within requested time
4914 **
4915 ** Returns          Pointer to the TLE struct
4916 **
4917 *******************************************************************************/
4918 static void btm_sec_pairing_timeout (TIMER_LIST_ENT *p_tle)
4919 {
4920     tBTM_CB *p_cb = &btm_cb;
4921     tBTM_SEC_DEV_REC *p_dev_rec;
4922 #if BTM_OOB_INCLUDED == TRUE
4923 #if (BTM_LOCAL_IO_CAPS == BTM_IO_CAP_NONE)
4924     tBTM_AUTH_REQ   auth_req = BTM_AUTH_AP_NO;
4925 #else
4926     tBTM_AUTH_REQ   auth_req = BTM_AUTH_AP_YES;
4927 #endif
4928 #endif
4929     UINT8   name[2];
4930     UNUSED(p_tle);
4931
4932     p_cb->pairing_tle.param = 0;
4933 /* Coverity: FALSE-POSITIVE error from Coverity tool. Please do NOT remove following comment. */
4934 /* coverity[UNUSED_VALUE] pointer p_dev_rec is actually used several times... This is a Coverity false-positive, i.e. a fake issue.
4935 */
4936     p_dev_rec = btm_find_dev (p_cb->pairing_bda);
4937
4938     BTM_TRACE_EVENT ("btm_sec_pairing_timeout()  State: %s   Flags: %u",
4939                       btm_pair_state_descr(p_cb->pairing_state), p_cb->pairing_flags);
4940
4941     switch (p_cb->pairing_state)
4942     {
4943         case BTM_PAIR_STATE_WAIT_PIN_REQ:
4944             btm_sec_bond_cancel_complete();
4945             break;
4946
4947         case BTM_PAIR_STATE_WAIT_LOCAL_PIN:
4948             if ( (btm_cb.pairing_flags & BTM_PAIR_FLAGS_PRE_FETCH_PIN) == 0)
4949                 btsnd_hcic_pin_code_neg_reply (p_cb->pairing_bda);
4950             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4951             /* We need to notify the UI that no longer need the PIN */
4952             if (btm_cb.api.p_auth_complete_callback)
4953             {
4954                 if (p_dev_rec == NULL)
4955                 {
4956                     name[0] = 0;
4957                     (*btm_cb.api.p_auth_complete_callback) (p_cb->pairing_bda,
4958                                                             NULL,
4959                                                             name, HCI_ERR_CONNECTION_TOUT);
4960                 }
4961                 else
4962                     (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
4963                                                             p_dev_rec->dev_class,
4964                                                             p_dev_rec->sec_bd_name, HCI_ERR_CONNECTION_TOUT);
4965             }
4966             break;
4967
4968         case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM:
4969             btsnd_hcic_user_conf_reply (p_cb->pairing_bda, FALSE);
4970             /* btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); */
4971             break;
4972
4973 #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE)
4974         case BTM_PAIR_STATE_KEY_ENTRY:
4975             btsnd_hcic_user_passkey_neg_reply(p_cb->pairing_bda);
4976             /* btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); */
4977             break;
4978 #endif /* !BTM_IO_CAP_NONE */
4979
4980 #if BTM_OOB_INCLUDED == TRUE
4981         case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS:
4982             if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
4983                 auth_req |= BTM_AUTH_DD_BOND;
4984
4985             btsnd_hcic_io_cap_req_reply (p_cb->pairing_bda, btm_cb.devcb.loc_io_caps,
4986                                          BTM_OOB_NONE, auth_req);
4987             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4988             break;
4989
4990         case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP:
4991             btsnd_hcic_rem_oob_neg_reply (p_cb->pairing_bda);
4992             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
4993             break;
4994 #endif /* BTM_OOB_INCLUDED */
4995
4996         case BTM_PAIR_STATE_WAIT_DISCONNECT:
4997             /* simple pairing failed. Started a 1-sec timer at simple pairing complete.
4998              * now it's time to tear down the ACL link*/
4999             if (p_dev_rec == NULL)
5000             {
5001                 BTM_TRACE_ERROR ("btm_sec_pairing_timeout() BTM_PAIR_STATE_WAIT_DISCONNECT unknown BDA: %08x%04x",
5002                                   (p_cb->pairing_bda[0]<<24) + (p_cb->pairing_bda[1]<<16) + (p_cb->pairing_bda[2]<<8) + p_cb->pairing_bda[3],
5003                                   (p_cb->pairing_bda[4] << 8) + p_cb->pairing_bda[5]);
5004                 break;
5005             }
5006             btm_sec_send_hci_disconnect (p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle);
5007             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
5008             break;
5009
5010         case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE:
5011             /* We need to notify the UI that timeout has happened while waiting for authentication*/
5012             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
5013             if (btm_cb.api.p_auth_complete_callback)
5014             {
5015                 if (p_dev_rec == NULL)
5016                 {
5017                     name[0] = 0;
5018                     (*btm_cb.api.p_auth_complete_callback) (p_cb->pairing_bda,
5019                                                             NULL,
5020                                                             name, HCI_ERR_CONNECTION_TOUT);
5021                 }
5022                 else
5023                     (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
5024                                                             p_dev_rec->dev_class,
5025                                                             p_dev_rec->sec_bd_name, HCI_ERR_CONNECTION_TOUT);
5026             }
5027             break;
5028
5029         default:
5030             BTM_TRACE_WARNING ("btm_sec_pairing_timeout() not processed state: %s", btm_pair_state_descr(btm_cb.pairing_state));
5031             btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
5032             break;
5033     }
5034 }
5035
5036 /*******************************************************************************
5037 **
5038 ** Function         btm_sec_pin_code_request
5039 **
5040 ** Description      This function is called when controller requests PIN code
5041 **
5042 ** Returns          Pointer to the record or NULL
5043 **
5044 *******************************************************************************/
5045 void btm_sec_pin_code_request (UINT8 *p_bda)
5046 {
5047     tBTM_SEC_DEV_REC *p_dev_rec;
5048     tBTM_CB          *p_cb = &btm_cb;
5049
5050 #ifdef PORCHE_PAIRING_CONFLICT
5051     UINT8 default_pin_code_len = 4;
5052     PIN_CODE default_pin_code = {0x30, 0x30, 0x30, 0x30};
5053 #endif
5054     BTM_TRACE_EVENT ("btm_sec_pin_code_request()  State: %s, BDA:%04x%08x",
5055                       btm_pair_state_descr(btm_cb.pairing_state),
5056                       (p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] );
5057
5058     if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)
5059     {
5060         if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0)  &&
5061              (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) )
5062         {
5063              /* fake this out - porshe carkit issue - */
5064 //            btm_cb.pairing_state = BTM_PAIR_STATE_IDLE;
5065              if(! btm_cb.pin_code_len_saved)
5066              {
5067                  btsnd_hcic_pin_code_neg_reply (p_bda);
5068                  return;
5069              }
5070              else
5071              {
5072                  btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code);
5073                  return;
5074              }
5075         }
5076         else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ)
5077                  || memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0)
5078         {
5079             BTM_TRACE_WARNING ("btm_sec_pin_code_request() rejected - state: %s",
5080                                 btm_pair_state_descr(btm_cb.pairing_state));
5081
5082 #ifdef PORCHE_PAIRING_CONFLICT
5083             /* reply pin code again due to counter in_rand when local initiates pairing */
5084             BTM_TRACE_EVENT ("btm_sec_pin_code_request from remote dev. for local initiated pairing");
5085             if(! btm_cb.pin_code_len_saved)
5086             {
5087                 btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
5088                 btsnd_hcic_pin_code_req_reply (p_bda, default_pin_code_len, default_pin_code);
5089             }
5090             else
5091             {
5092                 btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
5093                 btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code);
5094             }
5095 #else
5096             btsnd_hcic_pin_code_neg_reply (p_bda);
5097 #endif
5098             return;
5099         }
5100     }
5101
5102     p_dev_rec = btm_find_or_alloc_dev (p_bda);
5103     /* received PIN code request. must be non-sm4 */
5104     p_dev_rec->sm4 = BTM_SM4_KNOWN;
5105
5106     if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE)
5107     {
5108         memcpy (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN);
5109
5110         btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD;
5111         /* Make sure we reset the trusted mask to help against attacks */
5112         BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask);
5113     }
5114
5115     if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED))
5116     {
5117         BTM_TRACE_EVENT ("btm_sec_pin_code_request fixed pin replying");
5118         btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
5119         btsnd_hcic_pin_code_req_reply (p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code);
5120         return;
5121     }
5122
5123     /* Use the connecting device's CoD for the connection */
5124     if ( (!memcmp (p_bda, p_cb->connecting_bda, BD_ADDR_LEN))
5125          &&  (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] || p_cb->connecting_dc[2]) )
5126         memcpy (p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN);
5127
5128     /* We could have started connection after asking user for the PIN code */
5129     if (btm_cb.pin_code_len != 0)
5130     {
5131         BTM_TRACE_EVENT ("btm_sec_pin_code_request bonding sending reply");
5132         btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code);
5133
5134 #ifdef PORCHE_PAIRING_CONFLICT
5135         btm_cb.pin_code_len_saved = btm_cb.pin_code_len;
5136 #endif
5137
5138         /* Mark that we forwarded received from the user PIN code */
5139         btm_cb.pin_code_len = 0;
5140
5141         /* We can change mode back right away, that other connection being established */
5142         /* is not forced to be secure - found a FW issue, so we can not do this
5143         btm_restore_mode(); */
5144
5145         btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
5146     }
5147
5148     /* If pairing disabled OR (no PIN callback and not bonding) */
5149     /* OR we could not allocate entry in the database reject pairing request */
5150     else if (p_cb->pairing_disabled
5151              || (p_cb->api.p_pin_callback == NULL)
5152
5153              /* OR Microsoft keyboard can for some reason try to establish connection */
5154              /*  the only thing we can do here is to shut it up.  Normally we will be originator */
5155              /*  for keyboard bonding */
5156              || (!p_dev_rec->is_originator
5157                  && ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL)
5158                  &&  (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD)) )
5159     {
5160         BTM_TRACE_WARNING("btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev Rec:%x!",
5161                            p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec);
5162
5163         btsnd_hcic_pin_code_neg_reply (p_bda);
5164     }
5165     /* Notify upper layer of PIN request and start expiration timer */
5166     else
5167     {
5168         btm_cb.pin_code_len_saved = 0;
5169         btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN);
5170         /* Pin code request can not come at the same time as connection request */
5171         memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN);
5172         memcpy (p_cb->connecting_dc,  p_dev_rec->dev_class, DEV_CLASS_LEN);
5173
5174         /* Check if the name is known */
5175         /* Even if name is not known we might not be able to get one */
5176         /* this is the case when we are already getting something from the */
5177         /* device, so HCI level is flow controlled */
5178         /* Also cannot send remote name request while paging, i.e. connection is not completed */
5179         if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
5180         {
5181             BTM_TRACE_EVENT ("btm_sec_pin_code_request going for callback");
5182
5183             btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
5184             if (p_cb->api.p_pin_callback)
5185                 (*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
5186         }
5187         else
5188         {
5189             BTM_TRACE_EVENT ("btm_sec_pin_code_request going for remote name");
5190
5191             /* We received PIN code request for the device with unknown name */
5192             /* it is not user friendly just to ask for the PIN without name */
5193             /* try to get name at first */
5194             if (!btsnd_hcic_rmt_name_req (p_dev_rec->bd_addr,
5195                                           HCI_PAGE_SCAN_REP_MODE_R1,
5196                                           HCI_MANDATARY_PAGE_SCAN_MODE, 0))
5197             {
5198                 p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN;
5199                 p_dev_rec->sec_bd_name[0] = 'f';
5200                 p_dev_rec->sec_bd_name[1] = '0';
5201                 BTM_TRACE_ERROR ("can not send rmt_name_req?? fake a name and call callback");
5202
5203                 btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
5204                 if (p_cb->api.p_pin_callback)
5205                     (*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
5206             }
5207         }
5208     }
5209
5210     return;
5211 }
5212
5213 /*******************************************************************************
5214 **
5215 ** Function         btm_sec_update_clock_offset
5216 **
5217 ** Description      This function is called to update clock offset
5218 **
5219 ** Returns          void
5220 **
5221 *******************************************************************************/
5222 void btm_sec_update_clock_offset (UINT16 handle, UINT16 clock_offset)
5223 {
5224     tBTM_SEC_DEV_REC  *p_dev_rec;
5225     tBTM_INQ_INFO     *p_inq_info;
5226
5227     if ((p_dev_rec = btm_find_dev_by_handle (handle)) == NULL)
5228         return;
5229
5230     p_dev_rec->clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID;
5231
5232     if ((p_inq_info = BTM_InqDbRead(p_dev_rec->bd_addr)) == NULL)
5233         return;
5234
5235     p_inq_info->results.clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID;
5236 }
5237
5238
5239 /******************************************************************
5240 ** S T A T I C     F U N C T I O N S
5241 *******************************************************************/
5242
5243 /*******************************************************************************
5244 **
5245 ** Function         btm_sec_execute_procedure
5246 **
5247 ** Description      This function is called to start required security
5248 **                  procedure.  There is a case when multiplexing protocol
5249 **                  calls this function on the originating side, connection to
5250 **                  the peer will not be established.  This function in this
5251 **                  case performs only authorization.
5252 **
5253 ** Returns          BTM_SUCCESS     - permission is granted
5254 **                  BTM_CMD_STARTED - in process
5255 **                  BTM_NO_RESOURCES  - permission declined
5256 **
5257 *******************************************************************************/
5258 static tBTM_STATUS btm_sec_execute_procedure (tBTM_SEC_DEV_REC *p_dev_rec)
5259 {
5260     BTM_TRACE_EVENT ("btm_sec_execute_procedure: Required:0x%x Flags:0x%x State:%d",
5261                       p_dev_rec->security_required, p_dev_rec->sec_flags, p_dev_rec->sec_state);
5262
5263     /* There is a chance that we are getting name.  Wait until done. */
5264     if (p_dev_rec->sec_state != 0)
5265         return(BTM_CMD_STARTED);
5266
5267     /* If any security is required, get the name first */
5268     if (!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
5269         && (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE))
5270     {
5271         BTM_TRACE_EVENT ("Security Manager: Start get name");
5272         if (!btm_sec_start_get_name (p_dev_rec))
5273         {
5274             return(BTM_NO_RESOURCES);
5275         }
5276         return(BTM_CMD_STARTED);
5277     }
5278
5279     /* If connection is not authenticated and authentication is required */
5280     /* start authentication and return PENDING to the caller */
5281     if ((!(p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))
5282         && (( p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE))
5283             || (!p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_IN_AUTHENTICATE)))
5284         && (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE))
5285     {
5286 #if (L2CAP_UCD_INCLUDED == TRUE)
5287         /* if incoming UCD packet, discard it */
5288         if ( !p_dev_rec->is_originator && (p_dev_rec->is_ucd == TRUE ))
5289             return(BTM_FAILED_ON_SECURITY);
5290 #endif
5291
5292         BTM_TRACE_EVENT ("Security Manager: Start authentication");
5293
5294         if (!btm_sec_start_authentication (p_dev_rec))
5295         {
5296             return(BTM_NO_RESOURCES);
5297         }
5298         return(BTM_CMD_STARTED);
5299     }
5300
5301     /* If connection is not encrypted and encryption is required */
5302     /* start encryption and return PENDING to the caller */
5303     if (!(p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED)
5304         && (( p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_OUT_ENCRYPT))
5305             || (!p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_IN_ENCRYPT)))
5306         && (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE))
5307     {
5308 #if (L2CAP_UCD_INCLUDED == TRUE)
5309         /* if incoming UCD packet, discard it */
5310         if ( !p_dev_rec->is_originator && (p_dev_rec->is_ucd == TRUE ))
5311             return(BTM_FAILED_ON_SECURITY);
5312 #endif
5313
5314         BTM_TRACE_EVENT ("Security Manager: Start encryption");
5315
5316         if (!btm_sec_start_encryption (p_dev_rec))
5317         {
5318             return(BTM_NO_RESOURCES);
5319         }
5320         return(BTM_CMD_STARTED);
5321     }
5322
5323     if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) &&
5324         (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
5325     {
5326         BTM_TRACE_EVENT("%s: Security Manager: SC only service, but link key type is 0x%02x -",
5327                         "security failure", __FUNCTION__, p_dev_rec->link_key_type);
5328         return (BTM_FAILED_ON_SECURITY);
5329     }
5330
5331     /* If connection is not authorized and authorization is required */
5332     /* start authorization and return PENDING to the caller */
5333     if (!(p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED)
5334         && (( p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_OUT_AUTHORIZE))
5335             || (!p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_IN_AUTHORIZE))))
5336     {
5337         BTM_TRACE_EVENT ("service id:%d, is trusted:%d",
5338                           p_dev_rec->p_cur_service->service_id,
5339                           (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
5340                                                       p_dev_rec->p_cur_service->service_id)));
5341         if ((btm_sec_are_all_trusted(p_dev_rec->trusted_mask) == FALSE) &&
5342             (p_dev_rec->p_cur_service->service_id < BTM_SEC_MAX_SERVICES) &&
5343             (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
5344                                         p_dev_rec->p_cur_service->service_id) == FALSE))
5345         {
5346             BTM_TRACE_EVENT ("Security Manager: Start authorization");
5347             return(btm_sec_start_authorization (p_dev_rec));
5348         }
5349     }
5350
5351     /* All required  security procedures already established */
5352     p_dev_rec->security_required &= ~(BTM_SEC_OUT_AUTHORIZE | BTM_SEC_IN_AUTHORIZE |
5353                                       BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_AUTHENTICATE |
5354                                       BTM_SEC_OUT_ENCRYPT | BTM_SEC_IN_ENCRYPT |
5355                                       BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER |
5356                                       BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE);
5357
5358     BTM_TRACE_EVENT ("Security Manager: trusted:0x%04x%04x", p_dev_rec->trusted_mask[1], p_dev_rec->trusted_mask[0]);
5359     BTM_TRACE_EVENT ("Security Manager: access granted");
5360
5361     return(BTM_SUCCESS);
5362 }
5363
5364
5365 /*******************************************************************************
5366 **
5367 ** Function         btm_sec_start_get_name
5368 **
5369 ** Description      This function is called to start get name procedure
5370 **
5371 ** Returns          TRUE if started
5372 **
5373 *******************************************************************************/
5374 static BOOLEAN btm_sec_start_get_name (tBTM_SEC_DEV_REC *p_dev_rec)
5375 {
5376     UINT8 tempstate = p_dev_rec->sec_state;
5377
5378     p_dev_rec->sec_state = BTM_SEC_STATE_GETTING_NAME;
5379
5380     /* Device should be connected, no need to provide correct page params */
5381     /* 0 and NULL are as timeout and callback params because they are not used in security get name case */
5382     if ((btm_initiate_rem_name (p_dev_rec->bd_addr, NULL, BTM_RMT_NAME_SEC,
5383                                 0, NULL)) != BTM_CMD_STARTED)
5384     {
5385         p_dev_rec->sec_state = tempstate;
5386         return(FALSE);
5387     }
5388
5389     return(TRUE);
5390 }
5391
5392 /*******************************************************************************
5393 **
5394 ** Function         btm_sec_start_authentication
5395 **
5396 ** Description      This function is called to start authentication
5397 **
5398 ** Returns          TRUE if started
5399 **
5400 *******************************************************************************/
5401 static BOOLEAN btm_sec_start_authentication (tBTM_SEC_DEV_REC *p_dev_rec)
5402 {
5403     p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
5404
5405     return(btsnd_hcic_auth_request (p_dev_rec->hci_handle));
5406 }
5407
5408 /*******************************************************************************
5409 **
5410 ** Function         btm_sec_start_encryption
5411 **
5412 ** Description      This function is called to start encryption
5413 **
5414 ** Returns          TRUE if started
5415 **
5416 *******************************************************************************/
5417 static BOOLEAN btm_sec_start_encryption (tBTM_SEC_DEV_REC *p_dev_rec)
5418 {
5419     if (!btsnd_hcic_set_conn_encrypt (p_dev_rec->hci_handle, TRUE))
5420         return(FALSE);
5421
5422     p_dev_rec->sec_state = BTM_SEC_STATE_ENCRYPTING;
5423     return(TRUE);
5424 }
5425
5426
5427 /*******************************************************************************
5428 **
5429 ** Function         btm_sec_start_authorization
5430 **
5431 ** Description      This function is called to start authorization
5432 **
5433 ** Returns          TRUE if started
5434 **
5435 *******************************************************************************/
5436 static UINT8 btm_sec_start_authorization (tBTM_SEC_DEV_REC *p_dev_rec)
5437 {
5438     UINT8    result;
5439     UINT8   *p_service_name = NULL;
5440     UINT8    service_id;
5441
5442     if ((p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN)
5443         || (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE))
5444     {
5445         if (!btm_cb.api.p_authorize_callback)
5446             return(BTM_MODE_UNSUPPORTED);
5447
5448         if (p_dev_rec->p_cur_service)
5449         {
5450 #if BTM_SEC_SERVICE_NAME_LEN > 0
5451             if (p_dev_rec->is_originator)
5452                 p_service_name = p_dev_rec->p_cur_service->orig_service_name;
5453             else
5454                 p_service_name = p_dev_rec->p_cur_service->term_service_name;
5455 #endif
5456             service_id = p_dev_rec->p_cur_service->service_id;
5457         }
5458         else
5459             service_id = 0;
5460
5461         /* Send authorization request if not already sent during this service connection */
5462         if (p_dev_rec->last_author_service_id == BTM_SEC_NO_LAST_SERVICE_ID
5463             || p_dev_rec->last_author_service_id != service_id)
5464         {
5465             p_dev_rec->sec_state = BTM_SEC_STATE_AUTHORIZING;
5466             result = (*btm_cb.api.p_authorize_callback) (p_dev_rec->bd_addr,
5467                                                      p_dev_rec->dev_class,
5468                                                      p_dev_rec->sec_bd_name,
5469                                                      p_service_name,
5470                                                      service_id,
5471                                                      p_dev_rec->is_originator);
5472         }
5473
5474         else    /* Already authorized once for this L2CAP bringup */
5475         {
5476             BTM_TRACE_DEBUG ("btm_sec_start_authorization: (Ignoring extra Authorization prompt for service %d)", service_id);
5477             return (BTM_SUCCESS);
5478         }
5479
5480         if (result == BTM_SUCCESS)
5481         {
5482             p_dev_rec->sec_flags |= BTM_SEC_AUTHORIZED;
5483
5484             /* Save the currently authorized service in case we are asked again by another multiplexer layer */
5485             if (!p_dev_rec->is_originator)
5486                 p_dev_rec->last_author_service_id = service_id;
5487
5488             p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
5489         }
5490         return(result);
5491     }
5492     btm_sec_start_get_name (p_dev_rec);
5493     return(BTM_CMD_STARTED);
5494 }
5495
5496 /*******************************************************************************
5497 **
5498 ** Function         btm_sec_are_all_trusted
5499 **
5500 ** Description      This function is called check if all services are trusted
5501 **
5502 ** Returns          TRUE if all are trusted, otherwise FALSE
5503 **
5504 *******************************************************************************/
5505 BOOLEAN btm_sec_are_all_trusted(UINT32 p_mask[])
5506 {
5507     UINT32 trusted_inx;
5508     for (trusted_inx = 0; trusted_inx < BTM_SEC_SERVICE_ARRAY_SIZE; trusted_inx++)
5509     {
5510         if (p_mask[trusted_inx] != BTM_SEC_TRUST_ALL)
5511             return(FALSE);
5512     }
5513
5514     return(TRUE);
5515 }
5516
5517 /*******************************************************************************
5518 **
5519 ** Function         btm_sec_find_first_serv
5520 **
5521 ** Description      Look for the first record in the service database
5522 **                  with specified PSM
5523 **
5524 ** Returns          Pointer to the record or NULL
5525 **
5526 *******************************************************************************/
5527 static tBTM_SEC_SERV_REC *btm_sec_find_first_serv (CONNECTION_TYPE conn_type, UINT16 psm)
5528 {
5529     tBTM_SEC_SERV_REC *p_serv_rec = &btm_cb.sec_serv_rec[0];
5530     int i;
5531     BOOLEAN is_originator;
5532
5533 #if (L2CAP_UCD_INCLUDED == TRUE)
5534
5535     if ( conn_type & CONNECTION_TYPE_ORIG_MASK )
5536         is_originator = TRUE;
5537     else
5538         is_originator = FALSE;
5539 #else
5540     is_originator = conn_type;
5541 #endif
5542
5543     if (is_originator && btm_cb.p_out_serv && btm_cb.p_out_serv->psm == psm)
5544     {
5545         /* If this is outgoing connection and the PSM matches p_out_serv,
5546          * use it as the current service */
5547         return btm_cb.p_out_serv;
5548     }
5549
5550     /* otherwise, just find the first record with the specified PSM */
5551     for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++)
5552     {
5553         if ( (p_serv_rec->security_flags & BTM_SEC_IN_USE) && (p_serv_rec->psm == psm) )
5554             return(p_serv_rec);
5555     }
5556     return(NULL);
5557 }
5558
5559
5560 /*******************************************************************************
5561 **
5562 ** Function         btm_sec_find_next_serv
5563 **
5564 ** Description      Look for the next record in the service database
5565 **                  with specified PSM
5566 **
5567 ** Returns          Pointer to the record or NULL
5568 **
5569 *******************************************************************************/
5570 static tBTM_SEC_SERV_REC *btm_sec_find_next_serv (tBTM_SEC_SERV_REC *p_cur)
5571 {
5572     tBTM_SEC_SERV_REC *p_serv_rec   = &btm_cb.sec_serv_rec[0];
5573     int               i;
5574
5575     for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++)
5576     {
5577         if ((p_serv_rec->security_flags & BTM_SEC_IN_USE)
5578             && (p_serv_rec->psm == p_cur->psm) )
5579         {
5580             if (p_cur != p_serv_rec)
5581             {
5582                 return(p_serv_rec);
5583             }
5584         }
5585     }
5586     return(NULL);
5587 }
5588
5589
5590 /*******************************************************************************
5591 **
5592 ** Function         btm_sec_find_mx_serv
5593 **
5594 ** Description      Look for the record in the service database with specified
5595 **                  PSM and multiplexor channel information
5596 **
5597 ** Returns          Pointer to the record or NULL
5598 **
5599 *******************************************************************************/
5600 static tBTM_SEC_SERV_REC *btm_sec_find_mx_serv (UINT8 is_originator, UINT16 psm,
5601                                                 UINT32 mx_proto_id, UINT32 mx_chan_id)
5602 {
5603     tBTM_SEC_SERV_REC *p_out_serv = btm_cb.p_out_serv;
5604     tBTM_SEC_SERV_REC *p_serv_rec = &btm_cb.sec_serv_rec[0];
5605     int i;
5606
5607     BTM_TRACE_DEBUG ("%s()", __func__);
5608     if (is_originator && p_out_serv && p_out_serv->psm == psm
5609         && p_out_serv->mx_proto_id == mx_proto_id
5610         && p_out_serv->orig_mx_chan_id == mx_chan_id)
5611     {
5612         /* If this is outgoing connection and the parameters match p_out_serv,
5613          * use it as the current service */
5614         return btm_cb.p_out_serv;
5615     }
5616
5617     /* otherwise, the old way */
5618     for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++)
5619     {
5620         if ((p_serv_rec->security_flags & BTM_SEC_IN_USE)
5621             && (p_serv_rec->psm == psm)
5622             && (p_serv_rec->mx_proto_id == mx_proto_id)
5623             && (( is_originator && (p_serv_rec->orig_mx_chan_id  == mx_chan_id))
5624                 || (!is_originator && (p_serv_rec->term_mx_chan_id  == mx_chan_id))))
5625         {
5626             return(p_serv_rec);
5627         }
5628     }
5629     return(NULL);
5630 }
5631
5632
5633 /*******************************************************************************
5634 **
5635 ** Function         btm_sec_collision_timeout
5636 **
5637 ** Description      Encryption could not start because of the collision
5638 **                  try to do it again
5639 **
5640 ** Returns          Pointer to the TLE struct
5641 **
5642 *******************************************************************************/
5643 static void btm_sec_collision_timeout (TIMER_LIST_ENT *p_tle)
5644 {
5645     UNUSED(p_tle);
5646
5647     BTM_TRACE_EVENT ("%s()", __func__);
5648     btm_cb.sec_collision_tle.param = 0;
5649
5650     tBTM_STATUS status = btm_sec_execute_procedure (btm_cb.p_collided_dev_rec);
5651
5652     /* If result is pending reply from the user or from the device is pending */
5653     if (status != BTM_CMD_STARTED)
5654     {
5655         /* There is no next procedure or start of procedure failed, notify the waiting layer */
5656         btm_sec_dev_rec_cback_event (btm_cb.p_collided_dev_rec, status, FALSE);
5657     }
5658 }
5659
5660 /*******************************************************************************
5661 **
5662 ** Function         btm_sec_link_key_request
5663 **
5664 ** Description      This function is called when controller requests link key
5665 **
5666 ** Returns          Pointer to the record or NULL
5667 **
5668 *******************************************************************************/
5669 static void btm_send_link_key_notif (tBTM_SEC_DEV_REC *p_dev_rec)
5670 {
5671     if (btm_cb.api.p_link_key_callback)
5672         (*btm_cb.api.p_link_key_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class,
5673                                            p_dev_rec->sec_bd_name, p_dev_rec->link_key,
5674                                            p_dev_rec->link_key_type);
5675 }
5676
5677 /*******************************************************************************
5678 **
5679 ** Function         BTM_ReadTrustedMask
5680 **
5681 ** Description      Get trusted mask for the peer device
5682 **
5683 ** Parameters:      bd_addr   - Address of the device
5684 **
5685 ** Returns          NULL, if the device record is not found.
5686 **                  otherwise, the trusted mask
5687 **
5688 *******************************************************************************/
5689 UINT32 * BTM_ReadTrustedMask (BD_ADDR bd_addr)
5690 {
5691     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bd_addr);
5692     if (p_dev_rec != NULL)
5693         return(p_dev_rec->trusted_mask);
5694     return NULL;
5695 }
5696
5697 /*******************************************************************************
5698 **
5699 ** Function         btm_restore_mode
5700 **
5701 ** Description      This function returns the security mode to previous setting
5702 **                  if it was changed during bonding.
5703 **
5704 **
5705 ** Parameters:      void
5706 **
5707 *******************************************************************************/
5708 static void btm_restore_mode(void)
5709 {
5710     if (btm_cb.security_mode_changed)
5711     {
5712         btm_cb.security_mode_changed = FALSE;
5713         BTM_TRACE_DEBUG("%s() Auth enable -> %d", __func__, (btm_cb.security_mode == BTM_SEC_MODE_LINK));
5714         btsnd_hcic_write_auth_enable ((UINT8)(btm_cb.security_mode == BTM_SEC_MODE_LINK));
5715     }
5716
5717     if (btm_cb.pin_type_changed)
5718     {
5719         btm_cb.pin_type_changed = FALSE;
5720         btsnd_hcic_write_pin_type (btm_cb.cfg.pin_type);
5721     }
5722 }
5723
5724
5725 /*******************************************************************************
5726 **
5727 ** Function         btm_sec_find_dev_by_sec_state
5728 **
5729 ** Description      Look for the record in the device database for the device
5730 **                  which is being authenticated or encrypted
5731 **
5732 ** Returns          Pointer to the record or NULL
5733 **
5734 *******************************************************************************/
5735 tBTM_SEC_DEV_REC *btm_sec_find_dev_by_sec_state (UINT8 state)
5736 {
5737     tBTM_SEC_DEV_REC *p_dev_rec = &btm_cb.sec_dev_rec[0];
5738
5739     for (int i = 0; i < BTM_SEC_MAX_DEVICE_RECORDS; i++, p_dev_rec++)
5740     {
5741         if ((p_dev_rec->sec_flags & BTM_SEC_IN_USE)
5742             && (p_dev_rec->sec_state == state))
5743             return(p_dev_rec);
5744     }
5745     return(NULL);
5746 }
5747
5748 /*******************************************************************************
5749 **
5750 ** Function         btm_sec_change_pairing_state
5751 **
5752 ** Description      This function is called to change pairing state
5753 **
5754 *******************************************************************************/
5755 static void btm_sec_change_pairing_state (tBTM_PAIRING_STATE new_state)
5756 {
5757     tBTM_PAIRING_STATE  old_state = btm_cb.pairing_state;
5758
5759     BTM_TRACE_EVENT ("%s()  Old: %s", __func__, btm_pair_state_descr(btm_cb.pairing_state));
5760     BTM_TRACE_EVENT ("%s()  New: %s pairing_flags:0x%x", __func__,
5761             btm_pair_state_descr(new_state), btm_cb.pairing_flags);
5762
5763     btm_cb.pairing_state = new_state;
5764
5765     if (new_state == BTM_PAIR_STATE_IDLE)
5766     {
5767         btu_stop_timer (&btm_cb.pairing_tle);
5768
5769         btm_cb.pairing_flags = 0;
5770         btm_cb.pin_code_len  = 0;
5771
5772         /* Make sure the the lcb shows we are not bonding */
5773         l2cu_update_lcb_4_bonding (btm_cb.pairing_bda, FALSE);
5774
5775         btm_restore_mode();
5776         btm_sec_check_pending_reqs();
5777         btm_inq_clear_ssp();
5778
5779         memset (btm_cb.pairing_bda, 0xFF, BD_ADDR_LEN);
5780     }
5781     else
5782     {
5783         /* If transitionng out of idle, mark the lcb as bonding */
5784         if (old_state == BTM_PAIR_STATE_IDLE)
5785             l2cu_update_lcb_4_bonding (btm_cb.pairing_bda, TRUE);
5786
5787         btm_cb.pairing_tle.param = (TIMER_PARAM_TYPE)btm_sec_pairing_timeout;
5788
5789         btu_start_timer (&btm_cb.pairing_tle, BTU_TTYPE_USER_FUNC, BTM_SEC_TIMEOUT_VALUE);
5790     }
5791 }
5792
5793
5794 /*******************************************************************************
5795 **
5796 ** Function         btm_pair_state_descr
5797 **
5798 ** Description      Return state description for tracing
5799 **
5800 *******************************************************************************/
5801 #if (BT_USE_TRACES == TRUE)
5802 static char *btm_pair_state_descr (tBTM_PAIRING_STATE state)
5803 {
5804 #if (BT_TRACE_VERBOSE == TRUE)
5805     switch (state)
5806     {
5807         case BTM_PAIR_STATE_IDLE:                   return("IDLE");
5808         case BTM_PAIR_STATE_GET_REM_NAME:           return("GET_REM_NAME");
5809         case BTM_PAIR_STATE_WAIT_PIN_REQ:           return("WAIT_PIN_REQ");
5810         case BTM_PAIR_STATE_WAIT_LOCAL_PIN:         return("WAIT_LOCAL_PIN");
5811         case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM:   return("WAIT_NUM_CONFIRM");
5812         case BTM_PAIR_STATE_KEY_ENTRY:              return("KEY_ENTRY");
5813         case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP:     return("WAIT_LOCAL_OOB_RSP");
5814         case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS:      return("WAIT_LOCAL_IOCAPS");
5815         case BTM_PAIR_STATE_INCOMING_SSP:           return("INCOMING_SSP");
5816         case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE:     return("WAIT_AUTH_COMPLETE");
5817         case BTM_PAIR_STATE_WAIT_DISCONNECT:        return("WAIT_DISCONNECT");
5818     }
5819
5820     return("???");
5821 #else
5822     sprintf(btm_cb.state_temp_buffer,"%hhu",state);
5823
5824     return(btm_cb.state_temp_buffer);
5825 #endif
5826 }
5827 #endif
5828
5829 /*******************************************************************************
5830 **
5831 ** Function         btm_sec_dev_rec_cback_event
5832 **
5833 ** Description      This function calls the callback function with the given
5834 **                  result and clear the callback function.
5835 **
5836 ** Parameters:      void
5837 **
5838 *******************************************************************************/
5839 void btm_sec_dev_rec_cback_event (tBTM_SEC_DEV_REC *p_dev_rec, UINT8 res, BOOLEAN is_le_transport)
5840 {
5841     tBTM_SEC_CALLBACK   *p_callback = p_dev_rec->p_callback;
5842     tBT_TRANSPORT transport = is_le_transport ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR;
5843
5844     if (p_dev_rec->p_callback)
5845     {
5846         p_dev_rec->p_callback = NULL;
5847         (*p_callback) (p_dev_rec->bd_addr, transport, p_dev_rec->p_ref_data, res);
5848     }
5849
5850     btm_sec_check_pending_reqs();
5851 }
5852
5853 /*******************************************************************************
5854 **
5855 ** Function         btm_sec_queue_mx_request
5856 **
5857 ** Description      Return state description for tracing
5858 **
5859 *******************************************************************************/
5860 static BOOLEAN btm_sec_queue_mx_request (BD_ADDR bd_addr,  UINT16 psm,  BOOLEAN is_orig,
5861                                          UINT32 mx_proto_id, UINT32 mx_chan_id,
5862                                          tBTM_SEC_CALLBACK *p_callback, void *p_ref_data)
5863 {
5864     tBTM_SEC_QUEUE_ENTRY *p_e = (tBTM_SEC_QUEUE_ENTRY *)GKI_getbuf (sizeof(tBTM_SEC_QUEUE_ENTRY));
5865
5866     if (p_e)
5867     {
5868         p_e->psm            = psm;
5869         p_e->is_orig        = is_orig;
5870         p_e->p_callback     = p_callback;
5871         p_e->p_ref_data     = p_ref_data;
5872         p_e->mx_proto_id    = mx_proto_id;
5873         p_e->mx_chan_id     = mx_chan_id;
5874         p_e->transport      = BT_TRANSPORT_BR_EDR;
5875
5876         memcpy (p_e->bd_addr, bd_addr, BD_ADDR_LEN);
5877
5878         BTM_TRACE_EVENT ("%s() PSM: 0x%04x  Is_Orig: %u  mx_proto_id: %u  mx_chan_id: %u",
5879                           __func__, psm, is_orig, mx_proto_id, mx_chan_id);
5880
5881         GKI_enqueue (&btm_cb.sec_pending_q, p_e);
5882
5883         return(TRUE);
5884     }
5885
5886     return(FALSE);
5887 }
5888
5889 static BOOLEAN btm_sec_check_prefetch_pin (tBTM_SEC_DEV_REC  *p_dev_rec)
5890 {
5891     UINT8 major = (UINT8)(p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK);
5892     UINT8 minor = (UINT8)(p_dev_rec->dev_class[2] & BTM_COD_MINOR_CLASS_MASK);
5893     BOOLEAN rv = FALSE;
5894
5895     if ((major == BTM_COD_MAJOR_AUDIO)
5896         &&  ((minor == BTM_COD_MINOR_CONFM_HANDSFREE) || (minor == BTM_COD_MINOR_CAR_AUDIO)) )
5897     {
5898         BTM_TRACE_EVENT ("%s() Skipping pre-fetch PIN for carkit COD Major: 0x%02x Minor: 0x%02x",
5899             __func__, major, minor);
5900
5901         if (btm_cb.security_mode_changed == FALSE)
5902         {
5903             btm_cb.security_mode_changed = TRUE;
5904 #ifdef APPL_AUTH_WRITE_EXCEPTION
5905             if(!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr))
5906 #endif
5907                 btsnd_hcic_write_auth_enable (TRUE);
5908         }
5909     }
5910     else
5911     {
5912         btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN);
5913
5914         /* If we got a PIN, use that, else try to get one */
5915         if (btm_cb.pin_code_len)
5916         {
5917             BTM_PINCodeReply (p_dev_rec->bd_addr, BTM_SUCCESS, btm_cb.pin_code_len, btm_cb.pin_code, p_dev_rec->trusted_mask);
5918         }
5919         else
5920         {
5921             /* pin was not supplied - pre-fetch pin code now */
5922             if (btm_cb.api.p_pin_callback && ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0))
5923             {
5924                 BTM_TRACE_DEBUG("%s() PIN code callback called", __func__);
5925                 if (btm_bda_to_acl(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR) == NULL)
5926                 btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
5927                 (btm_cb.api.p_pin_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name);
5928             }
5929         }
5930
5931         rv = TRUE;
5932     }
5933
5934     return rv;
5935 }
5936
5937 /*******************************************************************************
5938 **
5939 ** Function         btm_sec_auth_payload_tout
5940 **
5941 ** Description      Processes the HCI Autheniticated Payload Timeout Event
5942 **                  indicating that a packet containing a valid MIC on the
5943 **                  connection handle was not received within the programmed
5944 **                  timeout value. (Spec Default is 30 secs, but can be
5945 **                  changed via the BTM_SecSetAuthPayloadTimeout() function.
5946 **
5947 *******************************************************************************/
5948 void btm_sec_auth_payload_tout (UINT8 *p, UINT16 hci_evt_len)
5949 {
5950     UINT16 handle;
5951
5952     STREAM_TO_UINT16 (handle, p);
5953     handle = HCID_GET_HANDLE (handle);
5954
5955     /* Will be exposed to upper layers in the future if/when determined necessary */
5956     BTM_TRACE_ERROR ("%s on handle 0x%02x", __func__, handle);
5957 }
5958
5959 /*******************************************************************************
5960 **
5961 ** Function         btm_sec_queue_encrypt_request
5962 **
5963 ** Description      encqueue encryption request when device has active security
5964 **                  process pending.
5965 **
5966 *******************************************************************************/
5967 static BOOLEAN btm_sec_queue_encrypt_request (BD_ADDR bd_addr, tBT_TRANSPORT transport,
5968                                          tBTM_SEC_CALLBACK *p_callback, void *p_ref_data)
5969 {
5970     tBTM_SEC_QUEUE_ENTRY  *p_e;
5971     p_e = (tBTM_SEC_QUEUE_ENTRY *)GKI_getbuf(sizeof(tBTM_SEC_QUEUE_ENTRY) + 1);
5972
5973     if (p_e)
5974     {
5975         p_e->psm  = 0;  /* if PSM 0, encryption request */
5976         p_e->p_callback  = p_callback;
5977         p_e->p_ref_data = (void *)(p_e + 1);
5978         *(UINT8 *)p_e->p_ref_data = *(UINT8 *)(p_ref_data);
5979         p_e->transport  = transport;
5980         memcpy(p_e->bd_addr, bd_addr, BD_ADDR_LEN);
5981         GKI_enqueue(&btm_cb.sec_pending_q, p_e);
5982         return TRUE;
5983     }
5984
5985     return FALSE;
5986 }
5987
5988 /*******************************************************************************
5989 **
5990 ** Function         btm_sec_set_peer_sec_caps
5991 **
5992 ** Description      This function is called to set sm4 and rmt_sec_caps fields
5993 **                  based on the available peer device features.
5994 **
5995 ** Returns          void
5996 **
5997 *******************************************************************************/
5998 void btm_sec_set_peer_sec_caps(tACL_CONN *p_acl_cb, tBTM_SEC_DEV_REC *p_dev_rec)
5999 {
6000     BD_ADDR     rem_bd_addr;
6001     UINT8       *p_rem_bd_addr;
6002
6003     if ((btm_cb.security_mode == BTM_SEC_MODE_SP ||
6004          btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG ||
6005          btm_cb.security_mode == BTM_SEC_MODE_SC) &&
6006         HCI_SSP_HOST_SUPPORTED(p_acl_cb->peer_lmp_features[HCI_EXT_FEATURES_PAGE_1]))
6007     {
6008         p_dev_rec->sm4 = BTM_SM4_TRUE;
6009         p_dev_rec->remote_supports_secure_connections =
6010             (HCI_SC_HOST_SUPPORTED(p_acl_cb->peer_lmp_features[HCI_EXT_FEATURES_PAGE_1]));
6011     }
6012     else
6013     {
6014         p_dev_rec->sm4 = BTM_SM4_KNOWN;
6015         p_dev_rec->remote_supports_secure_connections = FALSE;
6016     }
6017
6018     BTM_TRACE_API("%s: sm4: 0x%02x, rmt_support_for_secure_connections %d", __FUNCTION__,
6019                   p_dev_rec->sm4, p_dev_rec->remote_supports_secure_connections);
6020
6021
6022     if (p_dev_rec->remote_features_needed)
6023     {
6024         BTM_TRACE_EVENT("%s: Now device in SC Only mode, waiting for peer remote features!",
6025                         __FUNCTION__);
6026         p_rem_bd_addr = (UINT8*) rem_bd_addr;
6027         BDADDR_TO_STREAM(p_rem_bd_addr, p_dev_rec->bd_addr);
6028         p_rem_bd_addr = (UINT8*) rem_bd_addr;
6029         btm_io_capabilities_req(p_rem_bd_addr);
6030         p_dev_rec->remote_features_needed = FALSE;
6031     }
6032 }
6033
6034 /*******************************************************************************
6035 **
6036 ** Function         btm_sec_clean_pending_req_queue
6037 **
6038 ** Description      This function cleans up the pending security request when the
6039 **                  link to the target device dropped.
6040 **
6041 ** Returns          void
6042 **
6043 *******************************************************************************/
6044 static void btm_sec_clean_pending_req_queue (BD_ADDR remote_bda, tBT_TRANSPORT transport)
6045 {
6046     tBTM_SEC_QUEUE_ENTRY    *p_e;
6047     BUFFER_Q                *bq = &btm_cb.sec_pending_q;
6048
6049     p_e = (tBTM_SEC_QUEUE_ENTRY *)GKI_getfirst(bq);
6050
6051     if (p_e != NULL)
6052     {
6053         if (memcmp(p_e->bd_addr, remote_bda, BD_ADDR_LEN) == 0
6054 #if BLE_INCLUDED == TRUE
6055             && p_e->transport == transport
6056 #endif
6057             )
6058         {
6059             (*p_e->p_callback) (remote_bda, transport, p_e->p_ref_data, BTM_ERR_PROCESSING);
6060             GKI_remove_from_queue(bq, (void *)p_e);
6061         }
6062         p_e = (tBTM_SEC_QUEUE_ENTRY *) GKI_getnext ((void *)p_e);
6063     }
6064 }
6065
6066 /*******************************************************************************
6067 **
6068 ** Function         btm_sec_is_serv_level0
6069 **
6070 ** Description      This function is called to check if the service corresponding
6071 **                  to PSM is security mode 4 level 0 service.
6072 **
6073 ** Returns          TRUE if the service is security mode 4 level 0 service
6074 **
6075 *******************************************************************************/
6076 static BOOLEAN btm_sec_is_serv_level0(UINT16 psm)
6077 {
6078     if (psm == BT_PSM_SDP)
6079     {
6080         BTM_TRACE_DEBUG("%s: PSM: 0x%04x -> mode 4 level 0 service", __FUNCTION__, psm);
6081         return TRUE;
6082     }
6083     return FALSE;
6084 }
6085
6086 /*******************************************************************************
6087 **
6088 ** Function         btm_sec_check_pending_enc_req
6089 **
6090 ** Description      This function is called to send pending encryption callback if
6091 **                  waiting
6092 **
6093 ** Returns          void
6094 **
6095 *******************************************************************************/
6096 static void btm_sec_check_pending_enc_req (tBTM_SEC_DEV_REC  *p_dev_rec, tBT_TRANSPORT transport,
6097                                             UINT8 encr_enable)
6098 {
6099     tBTM_SEC_QUEUE_ENTRY    *p_e;
6100     BUFFER_Q                *bq = &btm_cb.sec_pending_q;
6101     UINT8                   res = encr_enable ? BTM_SUCCESS : BTM_ERR_PROCESSING;
6102     UINT8                   sec_act ;
6103
6104     p_e = (tBTM_SEC_QUEUE_ENTRY *)GKI_getfirst(bq);
6105
6106     while (p_e != NULL)
6107     {
6108         if (memcmp(p_e->bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN) == 0 && p_e->psm == 0
6109 #if BLE_INCLUDED == TRUE
6110             && p_e->transport == transport
6111 #endif
6112             )
6113         {
6114             sec_act = *(UINT8 *)(p_e->p_ref_data);
6115
6116             if (encr_enable == 0 || transport == BT_TRANSPORT_BR_EDR
6117 #if BLE_INCLUDED == TRUE
6118                 || (sec_act == BTM_BLE_SEC_ENCRYPT || sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM)
6119                 || (sec_act == BTM_BLE_SEC_ENCRYPT_MITM && p_dev_rec->sec_flags
6120                     & BTM_SEC_LE_AUTHENTICATED)
6121 #endif
6122                )
6123             {
6124                 (*p_e->p_callback) (p_dev_rec->bd_addr, transport, p_e->p_ref_data, res);
6125                 GKI_remove_from_queue(bq, (void *)p_e);
6126             }
6127         }
6128         p_e = (tBTM_SEC_QUEUE_ENTRY *) GKI_getnext ((void *)p_e);
6129     }
6130 }
6131
6132 /*******************************************************************************
6133 **
6134 ** Function         btm_sec_set_serv_level4_flags
6135 **
6136 ** Description      This function is called to set security mode 4 level 4 flags.
6137 **
6138 ** Returns          service security requirements updated to include secure
6139 **                  connections only mode.
6140 **
6141 *******************************************************************************/
6142 static UINT16 btm_sec_set_serv_level4_flags(UINT16 cur_security, BOOLEAN is_originator)
6143 {
6144     UINT16  sec_level4_flags = is_originator ? BTM_SEC_OUT_LEVEL4_FLAGS : BTM_SEC_IN_LEVEL4_FLAGS;
6145
6146     return cur_security | sec_level4_flags;
6147 }
6148
6149 #if (BLE_INCLUDED == TRUE)
6150 /*******************************************************************************
6151 **
6152 ** Function         btm_sec_clear_ble_keys
6153 **
6154 ** Description      This function is called to clear out the BLE keys.
6155 **                  Typically when devices are removed in BTM_SecDeleteDevice,
6156 **                  or when a new BT Link key is generated.
6157 **
6158 ** Returns          void
6159 **
6160 *******************************************************************************/
6161 void btm_sec_clear_ble_keys (tBTM_SEC_DEV_REC  *p_dev_rec)
6162 {
6163
6164     BTM_TRACE_DEBUG ("%s() Clearing BLE Keys", __func__);
6165 #if (SMP_INCLUDED== TRUE)
6166     p_dev_rec->ble.key_type = BTM_LE_KEY_NONE;
6167     memset (&p_dev_rec->ble.keys, 0, sizeof(tBTM_SEC_BLE_KEYS));
6168
6169 #if (BLE_PRIVACY_SPT == TRUE)
6170     btm_ble_resolving_list_remove_dev(p_dev_rec);
6171 #endif
6172 #endif
6173 }
6174
6175 /*******************************************************************************
6176 **
6177 ** Function         btm_sec_is_a_bonded_dev
6178 **
6179 ** Description       Is the specified device is a bonded device
6180 **
6181 ** Returns          TRUE - dev is bonded
6182 **
6183 *******************************************************************************/
6184 BOOLEAN btm_sec_is_a_bonded_dev (BD_ADDR bda)
6185 {
6186
6187     tBTM_SEC_DEV_REC *p_dev_rec= btm_find_dev (bda);
6188     BOOLEAN is_bonded= FALSE;
6189
6190     if (p_dev_rec &&
6191 #if (SMP_INCLUDED== TRUE)
6192         ((p_dev_rec->ble.key_type && (p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN))||
6193 #endif
6194          (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)))
6195     {
6196         is_bonded = TRUE;
6197     }
6198     BTM_TRACE_DEBUG ("%s() is_bonded=%d", __func__, is_bonded);
6199     return(is_bonded);
6200 }
6201
6202 /*******************************************************************************
6203 **
6204 ** Function         btm_sec_is_le_capable_dev
6205 **
6206 ** Description       Is the specified device is dual mode or LE only device
6207 **
6208 ** Returns          TRUE - dev is a dual mode
6209 **
6210 *******************************************************************************/
6211 BOOLEAN btm_sec_is_le_capable_dev (BD_ADDR bda)
6212 {
6213     tBTM_SEC_DEV_REC *p_dev_rec= btm_find_dev (bda);
6214     BOOLEAN le_capable = FALSE;
6215
6216 #if (BLE_INCLUDED== TRUE)
6217     if (p_dev_rec && ((p_dev_rec->device_type == BT_DEVICE_TYPE_DUMO) ||
6218          (p_dev_rec->device_type == BT_DEVICE_TYPE_BLE) ) )
6219     {
6220         le_capable  = TRUE;
6221     }
6222 #endif
6223     return le_capable;
6224 }
6225
6226 /*******************************************************************************
6227 **
6228 ** Function         btm_sec_find_bonded_dev
6229 **
6230 ** Description      Find a bonded device starting from the specified index
6231 **
6232 ** Returns          TRUE - found a bonded device
6233 **
6234 *******************************************************************************/
6235 BOOLEAN btm_sec_find_bonded_dev (UINT8 start_idx, UINT8 *p_found_idx, tBTM_SEC_DEV_REC **p_rec)
6236 {
6237     BOOLEAN found= FALSE;
6238
6239 #if (SMP_INCLUDED== TRUE)
6240     tBTM_SEC_DEV_REC *p_dev_rec;
6241     int i;
6242     if (start_idx >= BTM_SEC_MAX_DEVICE_RECORDS)
6243     {
6244         BTM_TRACE_DEBUG ("LE bonded device not found");
6245         return found;
6246     }
6247
6248     p_dev_rec = &btm_cb.sec_dev_rec[start_idx];
6249     for (i = start_idx; i < BTM_SEC_MAX_DEVICE_RECORDS; i++, p_dev_rec++)
6250     {
6251         if (p_dev_rec->ble.key_type || (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN))
6252         {
6253             *p_found_idx = i;
6254             *p_rec = p_dev_rec;
6255             break;
6256         }
6257     }
6258     BTM_TRACE_DEBUG ("%s() found=%d", __func__, found);
6259 #endif
6260     return(found);
6261 }
6262
6263 /*******************************************************************************
6264 **
6265 ** Function         btm_sec_use_smp_br_chnl
6266 **
6267 ** Description      The function checks if SMP BR connection can be used with
6268 **                  the peer.
6269 **                  Is called when authentication for dedicated bonding is
6270 **                  successfully completed.
6271 **
6272 ** Returns          TRUE - if SMP BR connection can be used (the link key is
6273 **                         generated from P-256 and the peer supports Security
6274 **                         Manager over BR).
6275 **
6276 *******************************************************************************/
6277 static BOOLEAN btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC *p_dev_rec)
6278 {
6279     UINT32  ext_feat;
6280     UINT8   chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE];
6281
6282     BTM_TRACE_DEBUG ("%s() link_key_type = 0x%x", __func__,
6283                       p_dev_rec->link_key_type);
6284
6285     if ((p_dev_rec->link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256) &&
6286         (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
6287          return FALSE;
6288
6289     if (!L2CA_GetPeerFeatures (p_dev_rec->bd_addr, &ext_feat, chnl_mask))
6290         return FALSE;
6291
6292     if (!(chnl_mask[0] & L2CAP_FIXED_CHNL_SMP_BR_BIT))
6293         return FALSE;
6294
6295     return TRUE;
6296 }
6297
6298 /*******************************************************************************
6299 **
6300 ** Function         btm_sec_is_master
6301 **
6302 ** Description      The function checks if the device is BR/EDR master after
6303 **                  pairing is completed.
6304 **
6305 ** Returns          TRUE - if the device is master.
6306 **
6307 *******************************************************************************/
6308 static BOOLEAN btm_sec_is_master(tBTM_SEC_DEV_REC *p_dev_rec)
6309 {
6310     tACL_CONN *p= btm_bda_to_acl(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR);
6311     return (p && (p->link_role == BTM_ROLE_MASTER));
6312 }
6313
6314 #endif /* BLE_INCLUDED */
6315