OSDN Git Service

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