xref: /btstack/src/hci.c (revision e4c6114d557b76c64cbcbafa2aeab10f6127021f)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "hci.c"
39 
40 /*
41  *  hci.c
42  *
43  *  Created by Matthias Ringwald on 4/29/09.
44  *
45  */
46 
47 #include "btstack_config.h"
48 
49 
50 #ifdef ENABLE_CLASSIC
51 #ifdef HAVE_EMBEDDED_TICK
52 #include "btstack_run_loop_embedded.h"
53 #endif
54 #endif
55 
56 #ifdef ENABLE_BLE
57 #include "gap.h"
58 #include "ble/le_device_db.h"
59 #endif
60 
61 #include <stdarg.h>
62 #include <string.h>
63 #include <inttypes.h>
64 
65 #include "btstack_debug.h"
66 #include "btstack_event.h"
67 #include "btstack_linked_list.h"
68 #include "btstack_memory.h"
69 #include "bluetooth_company_id.h"
70 #include "bluetooth_data_types.h"
71 #include "gap.h"
72 #include "hci.h"
73 #include "hci_cmd.h"
74 #include "hci_dump.h"
75 #include "ad_parser.h"
76 
77 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
78 #ifndef HCI_HOST_ACL_PACKET_NUM
79 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
80 #endif
81 #ifndef HCI_HOST_ACL_PACKET_LEN
82 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
83 #endif
84 #ifndef HCI_HOST_SCO_PACKET_NUM
85 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
86 #endif
87 #ifndef HCI_HOST_SCO_PACKET_LEN
88 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
89 #endif
90 #endif
91 
92 #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
93 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM."
94 #endif
95 
96 #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT)
97 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or HAVE_SCO_TRANSPORT."
98 #endif
99 
100 #define HCI_CONNECTION_TIMEOUT_MS 10000
101 
102 #ifndef HCI_RESET_RESEND_TIMEOUT_MS
103 #define HCI_RESET_RESEND_TIMEOUT_MS 200
104 #endif
105 
106 // Names are arbitrarily shortened to 32 bytes if not requested otherwise
107 #ifndef GAP_INQUIRY_MAX_NAME_LEN
108 #define GAP_INQUIRY_MAX_NAME_LEN 32
109 #endif
110 
111 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
112 #define GAP_INQUIRY_DURATION_MIN       0x01
113 #define GAP_INQUIRY_DURATION_MAX       0x30
114 #define GAP_INQUIRY_STATE_IDLE         0x00
115 #define GAP_INQUIRY_STATE_W4_ACTIVE    0x80
116 #define GAP_INQUIRY_STATE_ACTIVE       0x81
117 #define GAP_INQUIRY_STATE_W2_CANCEL    0x82
118 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83
119 
120 // GAP Remote Name Request
121 #define GAP_REMOTE_NAME_STATE_IDLE 0
122 #define GAP_REMOTE_NAME_STATE_W2_SEND 1
123 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
124 
125 // GAP Pairing
126 #define GAP_PAIRING_STATE_IDLE                       0
127 #define GAP_PAIRING_STATE_SEND_PIN                   1
128 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
129 #define GAP_PAIRING_STATE_SEND_PASSKEY               3
130 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
131 #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
132 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
133 #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE  7
134 
135 // prototypes
136 #ifdef ENABLE_CLASSIC
137 static void hci_update_scan_enable(void);
138 static void hci_emit_discoverable_enabled(uint8_t enabled);
139 static int  hci_local_ssp_activated(void);
140 static bool hci_remote_ssp_supported(hci_con_handle_t con_handle);
141 static bool hci_ssp_supported(hci_connection_t * connection);
142 static void hci_notify_if_sco_can_send_now(void);
143 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
144 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
145 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
146 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
147 static void hci_connection_timestamp(hci_connection_t *connection);
148 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
149 static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
150 #endif
151 
152 static int  hci_power_control_on(void);
153 static void hci_power_control_off(void);
154 static void hci_state_reset(void);
155 static void hci_emit_transport_packet_sent(void);
156 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
157 static void hci_emit_nr_connections_changed(void);
158 static void hci_emit_hci_open_failed(void);
159 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
160 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
161 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
162 static void hci_run(void);
163 static int  hci_is_le_connection(hci_connection_t * connection);
164 static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
165 
166 #ifdef ENABLE_CLASSIC
167 static int hci_have_usb_transport(void);
168 #endif
169 
170 #ifdef ENABLE_BLE
171 #ifdef ENABLE_LE_CENTRAL
172 // called from test/ble_client/advertising_data_parser.c
173 void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
174 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
175 static hci_connection_t * gap_get_outgoing_connection(void);
176 #endif
177 #endif
178 
179 // the STACK is here
180 #ifndef HAVE_MALLOC
181 static hci_stack_t   hci_stack_static;
182 #endif
183 static hci_stack_t * hci_stack = NULL;
184 
185 #ifdef ENABLE_CLASSIC
186 // default name
187 static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
188 
189 // test helper
190 static uint8_t disable_l2cap_timeouts = 0;
191 #endif
192 
193 // reset connection state on create and on reconnect
194 // don't overwrite addr, con handle, role
195 static void hci_connection_init(hci_connection_t * conn){
196     conn->authentication_flags = AUTH_FLAG_NONE;
197     conn->bonding_flags = 0;
198     conn->requested_security_level = LEVEL_0;
199 #ifdef ENABLE_CLASSIC
200     conn->request_role = HCI_ROLE_INVALID;
201     conn->sniff_subrating_max_latency = 0xffff;
202     conn->qos_service_type = HCI_SERVICE_TYPE_INVALID;
203     conn->link_key_type = INVALID_LINK_KEY;
204     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
205     btstack_run_loop_set_timer_context(&conn->timeout, conn);
206     hci_connection_timestamp(conn);
207 #endif
208     conn->acl_recombination_length = 0;
209     conn->acl_recombination_pos = 0;
210     conn->num_packets_sent = 0;
211 
212     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
213 #ifdef ENABLE_BLE
214     conn->le_phy_update_all_phys = 0xff;
215 #endif
216 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
217     conn->le_max_tx_octets = 27;
218 #endif
219 #ifdef ENABLE_CLASSIC_PAIRING_OOB
220     conn->classic_oob_c_192 = NULL;
221     conn->classic_oob_r_192 = NULL;
222     conn->classic_oob_c_256 = NULL;
223     conn->classic_oob_r_256 = NULL;
224 #endif
225 }
226 
227 /**
228  * create connection for given address
229  *
230  * @return connection OR NULL, if no memory left
231  */
232 static hci_connection_t * create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){
233     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
234 
235     hci_connection_t * conn = btstack_memory_hci_connection_get();
236     if (!conn) return NULL;
237     hci_connection_init(conn);
238 
239     bd_addr_copy(conn->address, addr);
240     conn->address_type = addr_type;
241     conn->con_handle = HCI_CON_HANDLE_INVALID;
242     conn->role = HCI_ROLE_INVALID;
243 
244     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
245 
246     return conn;
247 }
248 
249 
250 /**
251  * get le connection parameter range
252 *
253  * @return le connection parameter range struct
254  */
255 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
256     *range = hci_stack->le_connection_parameter_range;
257 }
258 
259 /**
260  * set le connection parameter range
261  *
262  */
263 
264 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
265     hci_stack->le_connection_parameter_range = *range;
266 }
267 
268 /**
269  * @brief Test if connection parameters are inside in existing rage
270  * @param conn_interval_min (unit: 1.25ms)
271  * @param conn_interval_max (unit: 1.25ms)
272  * @param conn_latency
273  * @param supervision_timeout (unit: 10ms)
274  * @returns 1 if included
275  */
276 int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){
277     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
278     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
279 
280     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
281     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
282 
283     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
284     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
285 
286     return 1;
287 }
288 
289 /**
290  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
291  * @note: default: 1
292  * @param max_peripheral_connections
293  */
294 #ifdef ENABLE_LE_PERIPHERAL
295 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
296     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
297 }
298 #endif
299 
300 /**
301  * get hci connections iterator
302  *
303  * @return hci connections iterator
304  */
305 
306 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
307     btstack_linked_list_iterator_init(it, &hci_stack->connections);
308 }
309 
310 /**
311  * get connection for a given handle
312  *
313  * @return connection OR NULL, if not found
314  */
315 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
316     btstack_linked_list_iterator_t it;
317     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
318     while (btstack_linked_list_iterator_has_next(&it)){
319         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
320         if ( item->con_handle == con_handle ) {
321             return item;
322         }
323     }
324     return NULL;
325 }
326 
327 /**
328  * get connection for given address
329  *
330  * @return connection OR NULL, if not found
331  */
332 hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
333     btstack_linked_list_iterator_t it;
334     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
335     while (btstack_linked_list_iterator_has_next(&it)){
336         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
337         if (connection->address_type != addr_type)  continue;
338         if (memcmp(addr, connection->address, 6) != 0) continue;
339         return connection;
340     }
341     return NULL;
342 }
343 
344 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
345     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
346 }
347 
348 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
349     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
350 }
351 
352 #ifdef ENABLE_CLASSIC
353 
354 #ifdef ENABLE_SCO_OVER_HCI
355 static int hci_number_sco_connections(void){
356     int connections = 0;
357     btstack_linked_list_iterator_t it;
358     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
359     while (btstack_linked_list_iterator_has_next(&it)){
360         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
361         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
362         connections++;
363     }
364     return connections;
365 }
366 #endif
367 
368 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
369     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
370 #ifdef HAVE_EMBEDDED_TICK
371     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
372         // connections might be timed out
373         hci_emit_l2cap_check_timeout(connection);
374     }
375 #else
376     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
377         // connections might be timed out
378         hci_emit_l2cap_check_timeout(connection);
379     }
380 #endif
381 }
382 
383 static void hci_connection_timestamp(hci_connection_t *connection){
384 #ifdef HAVE_EMBEDDED_TICK
385     connection->timestamp = btstack_run_loop_embedded_get_ticks();
386 #else
387     connection->timestamp = btstack_run_loop_get_time_ms();
388 #endif
389 }
390 
391 /**
392  * add authentication flags and reset timer
393  * @note: assumes classic connection
394  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
395  */
396 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
397     bd_addr_t addr;
398     reverse_bd_addr(bd_addr, addr);
399     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
400     if (conn) {
401         connectionSetAuthenticationFlags(conn, flags);
402         hci_connection_timestamp(conn);
403     }
404 }
405 
406 static bool hci_pairing_active(hci_connection_t * hci_connection){
407     return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0;
408 }
409 
410 static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){
411     if (hci_pairing_active(hci_connection)) return;
412     if (ssp){
413         hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE;
414     } else {
415         hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE;
416     }
417     // if we are initiator, we have sent an HCI Authenticate Request
418     bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0;
419 
420     // if we are responder, use minimal service security level as required level
421     if (!initiator){
422         hci_connection->requested_security_level = (gap_security_level_t) btstack_max((uint32_t) hci_connection->requested_security_level, (uint32_t) hci_stack->gap_minimal_service_security_level);
423     }
424 
425     log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level);
426 
427     uint8_t event[12];
428     event[0] = GAP_EVENT_PAIRING_STARTED;
429     event[1] = 10;
430     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
431     reverse_bd_addr(hci_connection->address, &event[4]);
432     event[10] = (uint8_t) ssp;
433     event[11] = (uint8_t) initiator;
434     hci_emit_event(event, sizeof(event), 1);
435 }
436 
437 static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){
438     hci_connection->requested_security_level = LEVEL_0;
439     if (!hci_pairing_active(hci_connection)) return;
440     hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK;
441 #ifdef ENABLE_CLASSIC_PAIRING_OOB
442     hci_connection->classic_oob_c_192 = NULL;
443     hci_connection->classic_oob_r_192 = NULL;
444     hci_connection->classic_oob_c_256 = NULL;
445     hci_connection->classic_oob_r_256 = NULL;
446 #endif
447     log_info("pairing complete, status %02x", status);
448 
449     uint8_t event[12];
450     event[0] = GAP_EVENT_PAIRING_COMPLETE;
451     event[1] = 9;
452     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
453     reverse_bd_addr(hci_connection->address, &event[4]);
454     event[10] = status;
455     hci_emit_event(event, sizeof(event), 1);
456 }
457 
458 bool hci_authentication_active_for_handle(hci_con_handle_t handle){
459     hci_connection_t * conn = hci_connection_for_handle(handle);
460     if (!conn) return false;
461     return hci_pairing_active(conn);
462 }
463 
464 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
465     if (!hci_stack->link_key_db) return;
466     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
467     hci_stack->link_key_db->delete_link_key(addr);
468 }
469 
470 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
471     if (!hci_stack->link_key_db) return;
472     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
473     hci_stack->link_key_db->put_link_key(addr, link_key, type);
474 }
475 
476 bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
477 	if (!hci_stack->link_key_db) return false;
478 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
479 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
480 	return result;
481 }
482 
483 void gap_delete_all_link_keys(void){
484     bd_addr_t  addr;
485     link_key_t link_key;
486     link_key_type_t type;
487     btstack_link_key_iterator_t it;
488     int ok = gap_link_key_iterator_init(&it);
489     if (!ok) {
490         log_error("could not initialize iterator");
491         return;
492     }
493     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
494         gap_drop_link_key_for_bd_addr(addr);
495     }
496     gap_link_key_iterator_done(&it);
497 }
498 
499 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
500     if (!hci_stack->link_key_db) return 0;
501     if (!hci_stack->link_key_db->iterator_init) return 0;
502     return hci_stack->link_key_db->iterator_init(it);
503 }
504 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){
505     if (!hci_stack->link_key_db) return 0;
506     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
507 }
508 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
509     if (!hci_stack->link_key_db) return;
510     hci_stack->link_key_db->iterator_done(it);
511 }
512 #endif
513 
514 static bool hci_is_le_connection_type(bd_addr_type_t address_type){
515     switch (address_type){
516         case BD_ADDR_TYPE_LE_PUBLIC:
517         case BD_ADDR_TYPE_LE_RANDOM:
518         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC:
519         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM:
520             return true;
521         default:
522             return false;
523     }
524 }
525 
526 static int hci_is_le_connection(hci_connection_t * connection){
527     return hci_is_le_connection_type(connection->address_type);
528 }
529 
530 /**
531  * count connections
532  */
533 static int nr_hci_connections(void){
534     int count = 0;
535     btstack_linked_item_t *it;
536     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
537         count++;
538     }
539     return count;
540 }
541 
542 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
543 
544     unsigned int num_packets_sent_classic = 0;
545     unsigned int num_packets_sent_le = 0;
546 
547     btstack_linked_item_t *it;
548     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
549         hci_connection_t * connection = (hci_connection_t *) it;
550         if (hci_is_le_connection(connection)){
551             num_packets_sent_le += connection->num_packets_sent;
552         }
553         if (connection->address_type == BD_ADDR_TYPE_ACL){
554             num_packets_sent_classic += connection->num_packets_sent;
555         }
556     }
557     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
558     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
559     int free_slots_le = 0;
560 
561     if (free_slots_classic < 0){
562         log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num);
563         return 0;
564     }
565 
566     if (hci_stack->le_acl_packets_total_num){
567         // if we have LE slots, they are used
568         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
569         if (free_slots_le < 0){
570             log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num);
571             return 0;
572         }
573     } else {
574         // otherwise, classic slots are used for LE, too
575         free_slots_classic -= num_packets_sent_le;
576         if (free_slots_classic < 0){
577             log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num);
578             return 0;
579         }
580     }
581 
582     switch (address_type){
583         case BD_ADDR_TYPE_UNKNOWN:
584             log_error("hci_number_free_acl_slots: unknown address type");
585             return 0;
586 
587         case BD_ADDR_TYPE_ACL:
588             return free_slots_classic;
589 
590         default:
591            if (hci_stack->le_acl_packets_total_num){
592                return free_slots_le;
593            }
594            return free_slots_classic;
595     }
596 }
597 
598 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
599     // get connection type
600     hci_connection_t * connection = hci_connection_for_handle(con_handle);
601     if (!connection){
602         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
603         return 0;
604     }
605     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
606 }
607 
608 #ifdef ENABLE_CLASSIC
609 static int hci_number_free_sco_slots(void){
610     unsigned int num_sco_packets_sent  = 0;
611     btstack_linked_item_t *it;
612     if (hci_stack->synchronous_flow_control_enabled){
613         // explicit flow control
614         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
615             hci_connection_t * connection = (hci_connection_t *) it;
616             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
617             num_sco_packets_sent += connection->num_packets_sent;
618         }
619         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
620             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
621             return 0;
622         }
623         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
624     } else {
625         // implicit flow control -- TODO
626         int num_ready = 0;
627         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
628             hci_connection_t * connection = (hci_connection_t *) it;
629             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
630             if (connection->sco_tx_ready == 0) continue;
631             num_ready++;
632         }
633         return num_ready;
634     }
635 }
636 #endif
637 
638 // only used to send HCI Host Number Completed Packets
639 static int hci_can_send_comand_packet_transport(void){
640     if (hci_stack->hci_packet_buffer_reserved) return 0;
641 
642     // check for async hci transport implementations
643     if (hci_stack->hci_transport->can_send_packet_now){
644         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
645             return 0;
646         }
647     }
648     return 1;
649 }
650 
651 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
652 bool hci_can_send_command_packet_now(void){
653     if (hci_can_send_comand_packet_transport() == 0) return false;
654     return hci_stack->num_cmd_packets > 0u;
655 }
656 
657 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
658     // check for async hci transport implementations
659     if (!hci_stack->hci_transport->can_send_packet_now) return true;
660     return hci_stack->hci_transport->can_send_packet_now(packet_type);
661 }
662 
663 static bool hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
664     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
665     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
666 }
667 
668 bool hci_can_send_acl_le_packet_now(void){
669     if (hci_stack->hci_packet_buffer_reserved) return false;
670     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
671 }
672 
673 bool hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
674     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
675     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
676 }
677 
678 bool hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
679     if (hci_stack->hci_packet_buffer_reserved) return false;
680     return hci_can_send_prepared_acl_packet_now(con_handle);
681 }
682 
683 #ifdef ENABLE_CLASSIC
684 bool hci_can_send_acl_classic_packet_now(void){
685     if (hci_stack->hci_packet_buffer_reserved) return false;
686     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
687 }
688 
689 bool hci_can_send_prepared_sco_packet_now(void){
690     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return false;
691     if (hci_have_usb_transport()){
692         return hci_stack->sco_can_send_now;
693     } else {
694         return hci_number_free_sco_slots() > 0;
695     }
696 }
697 
698 bool hci_can_send_sco_packet_now(void){
699     if (hci_stack->hci_packet_buffer_reserved) return false;
700     return hci_can_send_prepared_sco_packet_now();
701 }
702 
703 void hci_request_sco_can_send_now_event(void){
704     hci_stack->sco_waiting_for_can_send_now = 1;
705     hci_notify_if_sco_can_send_now();
706 }
707 #endif
708 
709 // used for internal checks in l2cap.c
710 bool hci_is_packet_buffer_reserved(void){
711     return hci_stack->hci_packet_buffer_reserved;
712 }
713 
714 // reserves outgoing packet buffer. @returns 1 if successful
715 bool hci_reserve_packet_buffer(void){
716     if (hci_stack->hci_packet_buffer_reserved) {
717         log_error("hci_reserve_packet_buffer called but buffer already reserved");
718         return false;
719     }
720     hci_stack->hci_packet_buffer_reserved = true;
721     return true;
722 }
723 
724 void hci_release_packet_buffer(void){
725     hci_stack->hci_packet_buffer_reserved = false;
726 }
727 
728 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
729 static int hci_transport_synchronous(void){
730     return hci_stack->hci_transport->can_send_packet_now == NULL;
731 }
732 
733 static uint8_t hci_send_acl_packet_fragments(hci_connection_t *connection){
734 
735     // log_info("hci_send_acl_packet_fragments  %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle);
736 
737     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
738     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
739     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
740         max_acl_data_packet_length = hci_stack->le_data_packets_length;
741     }
742 
743 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
744     if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){
745         max_acl_data_packet_length = connection->le_max_tx_octets;
746     }
747 #endif
748 
749     log_debug("hci_send_acl_packet_fragments entered");
750 
751     uint8_t status = ERROR_CODE_SUCCESS;
752     // multiple packets could be send on a synchronous HCI transport
753     while (true){
754 
755         log_debug("hci_send_acl_packet_fragments loop entered");
756 
757         // get current data
758         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
759         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
760         bool more_fragments = false;
761 
762         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
763         if (current_acl_data_packet_length > max_acl_data_packet_length){
764             more_fragments = true;
765             current_acl_data_packet_length = max_acl_data_packet_length;
766         }
767 
768         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
769         if (acl_header_pos > 0u){
770             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
771             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
772             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
773         }
774 
775         // update header len
776         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
777 
778         // count packet
779         connection->num_packets_sent++;
780         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
781 
782         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
783         if (more_fragments){
784             // update start of next fragment to send
785             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
786         } else {
787             // done
788             hci_stack->acl_fragmentation_pos = 0;
789             hci_stack->acl_fragmentation_total_size = 0;
790         }
791 
792         // send packet
793         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
794         const int size = current_acl_data_packet_length + 4;
795         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
796         hci_stack->acl_fragmentation_tx_active = 1;
797         int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
798         if (err != 0){
799             // no error from HCI Transport expected
800             status = ERROR_CODE_HARDWARE_FAILURE;
801         }
802 
803         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
804 
805         // done yet?
806         if (!more_fragments) break;
807 
808         // can send more?
809         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return status;
810     }
811 
812     log_debug("hci_send_acl_packet_fragments loop over");
813 
814     // release buffer now for synchronous transport
815     if (hci_transport_synchronous()){
816         hci_stack->acl_fragmentation_tx_active = 0;
817         hci_release_packet_buffer();
818         hci_emit_transport_packet_sent();
819     }
820 
821     return status;
822 }
823 
824 // pre: caller has reserved the packet buffer
825 uint8_t hci_send_acl_packet_buffer(int size){
826     btstack_assert(hci_stack->hci_packet_buffer_reserved);
827 
828     uint8_t * packet = hci_stack->hci_packet_buffer;
829     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
830 
831     // check for free places on Bluetooth module
832     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
833         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
834         hci_release_packet_buffer();
835         hci_emit_transport_packet_sent();
836         return BTSTACK_ACL_BUFFERS_FULL;
837     }
838 
839     hci_connection_t *connection = hci_connection_for_handle( con_handle);
840     if (!connection) {
841         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
842         hci_release_packet_buffer();
843         hci_emit_transport_packet_sent();
844         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
845     }
846 
847 #ifdef ENABLE_CLASSIC
848     hci_connection_timestamp(connection);
849 #endif
850 
851     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
852 
853     // setup data
854     hci_stack->acl_fragmentation_total_size = size;
855     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
856 
857     return hci_send_acl_packet_fragments(connection);
858 }
859 
860 #ifdef ENABLE_CLASSIC
861 // pre: caller has reserved the packet buffer
862 uint8_t hci_send_sco_packet_buffer(int size){
863     btstack_assert(hci_stack->hci_packet_buffer_reserved);
864 
865     uint8_t * packet = hci_stack->hci_packet_buffer;
866 
867     // skip checks in loopback mode
868     if (!hci_stack->loopback_mode){
869         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
870 
871         // check for free places on Bluetooth module
872         if (!hci_can_send_prepared_sco_packet_now()) {
873             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
874             hci_release_packet_buffer();
875             hci_emit_transport_packet_sent();
876             return BTSTACK_ACL_BUFFERS_FULL;
877         }
878 
879         // track send packet in connection struct
880         hci_connection_t *connection = hci_connection_for_handle( con_handle);
881         if (!connection) {
882             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
883             hci_release_packet_buffer();
884             hci_emit_transport_packet_sent();
885             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
886         }
887 
888         if (hci_have_usb_transport()){
889             // token used
890             hci_stack->sco_can_send_now = false;
891         } else {
892             if (hci_stack->synchronous_flow_control_enabled){
893                 connection->num_packets_sent++;
894             } else {
895                 connection->sco_tx_ready--;
896             }
897         }
898     }
899 
900     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
901 
902 #ifdef HAVE_SCO_TRANSPORT
903     hci_stack->sco_transport->send_packet(packet, size);
904     hci_release_packet_buffer();
905     hci_emit_transport_packet_sent();
906 
907     return 0;
908 #else
909     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
910     if (hci_transport_synchronous()){
911         hci_release_packet_buffer();
912         hci_emit_transport_packet_sent();
913     }
914 
915     if (err != 0){
916         return ERROR_CODE_HARDWARE_FAILURE;
917     }
918     return ERROR_CODE_SUCCESS;
919 #endif
920 }
921 #endif
922 
923 static void acl_handler(uint8_t *packet, uint16_t size){
924 
925     // get info
926     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
927     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
928     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
929     uint16_t acl_length         = READ_ACL_LENGTH(packet);
930 
931     // ignore non-registered handle
932     if (!conn){
933         log_error("acl_handler called with non-registered handle %u!" , con_handle);
934         return;
935     }
936 
937     // assert packet is complete
938     if ((acl_length + 4u) != size){
939         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
940         return;
941     }
942 
943 #ifdef ENABLE_CLASSIC
944     // update idle timestamp
945     hci_connection_timestamp(conn);
946 #endif
947 
948 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
949     hci_stack->host_completed_packets = 1;
950     conn->num_packets_completed++;
951 #endif
952 
953     // handle different packet types
954     switch (acl_flags & 0x03u) {
955 
956         case 0x01: // continuation fragment
957 
958             // sanity checks
959             if (conn->acl_recombination_pos == 0u) {
960                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
961                 return;
962             }
963             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
964                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
965                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
966                 conn->acl_recombination_pos = 0;
967                 return;
968             }
969 
970             // append fragment payload (header already stored)
971             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
972                          &packet[4], acl_length);
973             conn->acl_recombination_pos += acl_length;
974 
975             // forward complete L2CAP packet if complete.
976             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
977                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
978                 // reset recombination buffer
979                 conn->acl_recombination_length = 0;
980                 conn->acl_recombination_pos = 0;
981             }
982             break;
983 
984         case 0x02: { // first fragment
985 
986             // sanity check
987             if (conn->acl_recombination_pos) {
988                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
989                 conn->acl_recombination_pos = 0;
990             }
991 
992             // peek into L2CAP packet!
993             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
994 
995             // compare fragment size to L2CAP packet size
996             if (acl_length >= (l2cap_length + 4u)){
997                 // forward fragment as L2CAP packet
998                 hci_emit_acl_packet(packet, acl_length + 4u);
999             } else {
1000 
1001                 if (acl_length > HCI_ACL_BUFFER_SIZE){
1002                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
1003                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
1004                     return;
1005                 }
1006 
1007                 // store first fragment and tweak acl length for complete package
1008                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
1009                              packet, acl_length + 4u);
1010                 conn->acl_recombination_pos    = acl_length + 4u;
1011                 conn->acl_recombination_length = l2cap_length;
1012                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
1013             }
1014             break;
1015 
1016         }
1017         default:
1018             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
1019             return;
1020     }
1021 
1022     // execute main loop
1023     hci_run();
1024 }
1025 
1026 static void hci_connection_stop_timer(hci_connection_t * conn){
1027     btstack_run_loop_remove_timer(&conn->timeout);
1028 #ifdef ENABLE_CLASSIC
1029     btstack_run_loop_remove_timer(&conn->timeout_sco);
1030 #endif
1031 }
1032 
1033 static void hci_shutdown_connection(hci_connection_t *conn){
1034     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
1035 
1036 #ifdef ENABLE_CLASSIC
1037 #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1038     bd_addr_type_t addr_type = conn->address_type;
1039 #endif
1040 #ifdef HAVE_SCO_TRANSPORT
1041     hci_con_handle_t con_handle = conn->con_handle;
1042 #endif
1043 #endif
1044 
1045     hci_connection_stop_timer(conn);
1046 
1047     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1048     btstack_memory_hci_connection_free( conn );
1049 
1050     // now it's gone
1051     hci_emit_nr_connections_changed();
1052 
1053 #ifdef ENABLE_CLASSIC
1054 #ifdef ENABLE_SCO_OVER_HCI
1055     // update SCO
1056     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1057         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1058     }
1059 #endif
1060 #ifdef HAVE_SCO_TRANSPORT
1061     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1062         hci_stack->sco_transport->close(con_handle);
1063     }
1064 #endif
1065 #endif
1066 }
1067 
1068 #ifdef ENABLE_CLASSIC
1069 
1070 static const uint16_t packet_type_sizes[] = {
1071     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
1072     HCI_ACL_DH1_SIZE, 0, 0, 0,
1073     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
1074     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
1075 };
1076 static const uint8_t  packet_type_feature_requirement_bit[] = {
1077      0, // 3 slot packets
1078      1, // 5 slot packets
1079     25, // EDR 2 mpbs
1080     26, // EDR 3 mbps
1081     39, // 3 slot EDR packts
1082     40, // 5 slot EDR packet
1083 };
1084 static const uint16_t packet_type_feature_packet_mask[] = {
1085     0x0f00, // 3 slot packets
1086     0xf000, // 5 slot packets
1087     0x1102, // EDR 2 mpbs
1088     0x2204, // EDR 3 mbps
1089     0x0300, // 3 slot EDR packts
1090     0x3000, // 5 slot EDR packet
1091 };
1092 
1093 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
1094     // enable packet types based on size
1095     uint16_t packet_types = 0;
1096     unsigned int i;
1097     for (i=0;i<16;i++){
1098         if (packet_type_sizes[i] == 0) continue;
1099         if (packet_type_sizes[i] <= buffer_size){
1100             packet_types |= 1 << i;
1101         }
1102     }
1103     // disable packet types due to missing local supported features
1104     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
1105         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
1106         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1107         if (feature_set) continue;
1108         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
1109         packet_types &= ~packet_type_feature_packet_mask[i];
1110     }
1111     // flip bits for "may not be used"
1112     packet_types ^= 0x3306;
1113     return packet_types;
1114 }
1115 
1116 uint16_t hci_usable_acl_packet_types(void){
1117     return hci_stack->packet_types;
1118 }
1119 #endif
1120 
1121 uint8_t* hci_get_outgoing_packet_buffer(void){
1122     // hci packet buffer is >= acl data packet length
1123     return hci_stack->hci_packet_buffer;
1124 }
1125 
1126 uint16_t hci_max_acl_data_packet_length(void){
1127     return hci_stack->acl_data_packet_length;
1128 }
1129 
1130 #ifdef ENABLE_CLASSIC
1131 bool hci_extended_sco_link_supported(void){
1132     // No. 31, byte 3, bit 7
1133     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
1134 }
1135 #endif
1136 
1137 bool hci_non_flushable_packet_boundary_flag_supported(void){
1138     // No. 54, byte 6, bit 6
1139     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
1140 }
1141 
1142 static int gap_ssp_supported(void){
1143     // No. 51, byte 6, bit 3
1144     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1145 }
1146 
1147 static int hci_classic_supported(void){
1148 #ifdef ENABLE_CLASSIC
1149     // No. 37, byte 4, bit 5, = No BR/EDR Support
1150     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
1151 #else
1152     return 0;
1153 #endif
1154 }
1155 
1156 static int hci_le_supported(void){
1157 #ifdef ENABLE_BLE
1158     // No. 37, byte 4, bit 6 = LE Supported (Controller)
1159     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1160 #else
1161     return 0;
1162 #endif
1163 }
1164 
1165 #ifdef ENABLE_BLE
1166 
1167 static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
1168     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
1169         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
1170     } else {
1171         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
1172     }
1173 }
1174 
1175 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
1176     *addr_type = hci_stack->le_own_addr_type;
1177     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
1178 }
1179 
1180 #ifdef ENABLE_LE_PERIPHERAL
1181 void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
1182     *addr_type = hci_stack->le_advertisements_own_addr_type;
1183     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
1184 };
1185 #endif
1186 
1187 #ifdef ENABLE_LE_CENTRAL
1188 
1189 /**
1190  * @brief Get own addr type and address used for LE connections (Central)
1191  */
1192 void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
1193     *addr_type = hci_stack->le_connection_own_addr_type;
1194     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
1195 }
1196 
1197 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
1198 
1199     int offset = 3;
1200     int num_reports = packet[offset];
1201     offset += 1;
1202 
1203     int i;
1204     // log_info("HCI: handle adv report with num reports: %d", num_reports);
1205     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1206     for (i=0; (i<num_reports) && (offset < size);i++){
1207         // sanity checks on data_length:
1208         uint8_t data_length = packet[offset + 8];
1209         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1210         if ((offset + 9u + data_length + 1u) > size)    return;
1211         // setup event
1212         uint8_t event_size = 10u + data_length;
1213         int pos = 0;
1214         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1215         event[pos++] = event_size;
1216         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1217         offset += 8;
1218         pos += 8;
1219         event[pos++] = packet[offset + 1 + data_length]; // rssi
1220         event[pos++] = data_length;
1221         offset++;
1222         (void)memcpy(&event[pos], &packet[offset], data_length);
1223         pos +=    data_length;
1224         offset += data_length + 1u; // rssi
1225         hci_emit_event(event, pos, 1);
1226     }
1227 }
1228 #endif
1229 #endif
1230 
1231 #ifdef ENABLE_BLE
1232 #ifdef ENABLE_LE_PERIPHERAL
1233 static void hci_update_advertisements_enabled_for_current_roles(void){
1234     if (hci_stack->le_advertisements_enabled){
1235         // get number of active le slave connections
1236         int num_slave_connections = 0;
1237         btstack_linked_list_iterator_t it;
1238         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
1239         while (btstack_linked_list_iterator_has_next(&it)){
1240             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
1241             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
1242             if (con->state != OPEN) continue;
1243             if (con->role  != HCI_ROLE_SLAVE) continue;
1244             if (!hci_is_le_connection(con)) continue;
1245             num_slave_connections++;
1246         }
1247         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1248         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1249     } else {
1250         hci_stack->le_advertisements_enabled_for_current_roles = false;
1251     }
1252 }
1253 #endif
1254 #endif
1255 
1256 #ifdef ENABLE_CLASSIC
1257 static void gap_run_set_local_name(void){
1258     hci_reserve_packet_buffer();
1259     uint8_t * packet = hci_stack->hci_packet_buffer;
1260     // construct HCI Command and send
1261     uint16_t opcode = hci_write_local_name.opcode;
1262     hci_stack->last_cmd_opcode = opcode;
1263     packet[0] = opcode & 0xff;
1264     packet[1] = opcode >> 8;
1265     packet[2] = DEVICE_NAME_LEN;
1266     memset(&packet[3], 0, DEVICE_NAME_LEN);
1267     uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1268     uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
1269     // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
1270     (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
1271     // expand '00:00:00:00:00:00' in name with bd_addr
1272     btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
1273     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1274 }
1275 
1276 static void gap_run_set_eir_data(void){
1277     hci_reserve_packet_buffer();
1278     uint8_t * packet = hci_stack->hci_packet_buffer;
1279     // construct HCI Command in-place and send
1280     uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1281     hci_stack->last_cmd_opcode = opcode;
1282     uint16_t offset = 0;
1283     packet[offset++] = opcode & 0xff;
1284     packet[offset++] = opcode >> 8;
1285     packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
1286     packet[offset++] = 0;  // FEC not required
1287     memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1288     if (hci_stack->eir_data){
1289         // copy items and expand '00:00:00:00:00:00' in name with bd_addr
1290         ad_context_t context;
1291         for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
1292             uint8_t data_type   = ad_iterator_get_data_type(&context);
1293             uint8_t size        = ad_iterator_get_data_len(&context);
1294             const uint8_t *data = ad_iterator_get_data(&context);
1295             // copy item
1296             packet[offset++] = size + 1;
1297             packet[offset++] = data_type;
1298             memcpy(&packet[offset], data, size);
1299             // update name item
1300             if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
1301                 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
1302             }
1303             offset += size;
1304         }
1305     } else {
1306         uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1307         uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
1308         packet[offset++] = bytes_to_copy + 1;
1309         packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1310         (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
1311         // expand '00:00:00:00:00:00' in name with bd_addr
1312         btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
1313     }
1314     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1315 }
1316 
1317 static void hci_run_gap_tasks_classic(void){
1318     if ((hci_stack->gap_tasks & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
1319         hci_stack->gap_tasks &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
1320         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1321         return;
1322     }
1323     if ((hci_stack->gap_tasks & GAP_TASK_SET_LOCAL_NAME) != 0) {
1324         hci_stack->gap_tasks &= ~GAP_TASK_SET_LOCAL_NAME;
1325         gap_run_set_local_name();
1326         return;
1327     }
1328     if ((hci_stack->gap_tasks & GAP_TASK_SET_EIR_DATA) != 0) {
1329         hci_stack->gap_tasks &= ~GAP_TASK_SET_EIR_DATA;
1330         gap_run_set_eir_data();
1331         return;
1332     }
1333     if ((hci_stack->gap_tasks & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
1334         hci_stack->gap_tasks &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
1335         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1336         return;
1337     }
1338     // write page scan activity
1339     if ((hci_stack->gap_tasks & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) {
1340         hci_stack->gap_tasks &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
1341         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
1342         return;
1343     }
1344     // write page scan type
1345     if ((hci_stack->gap_tasks & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) {
1346         hci_stack->gap_tasks &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE;
1347         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
1348         return;
1349     }
1350     // send scan enable
1351     if ((hci_stack->gap_tasks & GAP_TASK_WRITE_SCAN_ENABLE) != 0) {
1352         hci_stack->gap_tasks &= ~GAP_TASK_WRITE_SCAN_ENABLE;
1353         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1354         return;
1355     }
1356 }
1357 #endif
1358 
1359 #ifndef HAVE_HOST_CONTROLLER_API
1360 
1361 static uint32_t hci_transport_uart_get_main_baud_rate(void){
1362     if (!hci_stack->config) return 0;
1363     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1364     // Limit baud rate for Broadcom chipsets to 3 mbps
1365     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
1366         baud_rate = 3000000;
1367     }
1368     return baud_rate;
1369 }
1370 
1371 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
1372     UNUSED(ds);
1373 
1374     switch (hci_stack->substate){
1375         case HCI_INIT_W4_SEND_RESET:
1376             log_info("Resend HCI Reset");
1377             hci_stack->substate = HCI_INIT_SEND_RESET;
1378             hci_stack->num_cmd_packets = 1;
1379             hci_run();
1380             break;
1381         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
1382             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
1383             if (hci_stack->hci_transport->reset_link){
1384                 hci_stack->hci_transport->reset_link();
1385             }
1386 
1387             /* fall through */
1388 
1389         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1390             log_info("Resend HCI Reset - CSR Warm Boot");
1391             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1392             hci_stack->num_cmd_packets = 1;
1393             hci_run();
1394             break;
1395         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1396             if (hci_stack->hci_transport->set_baudrate){
1397                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1398                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
1399                 hci_stack->hci_transport->set_baudrate(baud_rate);
1400             }
1401             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
1402             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1403                 if (hci_stack->hci_transport->reset_link){
1404                     log_info("Link Reset");
1405                     hci_stack->hci_transport->reset_link();
1406                 }
1407                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1408                 hci_run();
1409             }
1410             break;
1411         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1412             // otherwise continue
1413             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1414             hci_send_cmd(&hci_read_local_supported_commands);
1415             break;
1416         default:
1417             break;
1418     }
1419 }
1420 #endif
1421 
1422 static void hci_initializing_next_state(void){
1423     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
1424 }
1425 
1426 static void hci_init_done(void){
1427     // done. tell the app
1428     log_info("hci_init_done -> HCI_STATE_WORKING");
1429     hci_stack->state = HCI_STATE_WORKING;
1430     hci_emit_state();
1431 }
1432 
1433 // assumption: hci_can_send_command_packet_now() == true
1434 static void hci_initializing_run(void){
1435     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1436 
1437     bool need_baud_change = false;
1438 
1439 #ifndef HAVE_HOST_CONTROLLER_API
1440     need_baud_change = hci_stack->config
1441             && hci_stack->chipset
1442             && hci_stack->chipset->set_baudrate_command
1443             && hci_stack->hci_transport->set_baudrate
1444             && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1445 #endif
1446 
1447     switch (hci_stack->substate){
1448         case HCI_INIT_SEND_RESET:
1449             hci_state_reset();
1450 
1451 #ifndef HAVE_HOST_CONTROLLER_API
1452             // prepare reset if command complete not received in 100ms
1453             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1454             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1455             btstack_run_loop_add_timer(&hci_stack->timeout);
1456 #endif
1457             // send command
1458             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1459             hci_send_cmd(&hci_reset);
1460             break;
1461         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1462             hci_send_cmd(&hci_read_local_version_information);
1463             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1464             break;
1465         case HCI_INIT_SEND_READ_LOCAL_NAME:
1466             hci_send_cmd(&hci_read_local_name);
1467             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1468             break;
1469 
1470 #ifndef HAVE_HOST_CONTROLLER_API
1471         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1472             hci_state_reset();
1473             // prepare reset if command complete not received in 100ms
1474             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1475             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1476             btstack_run_loop_add_timer(&hci_stack->timeout);
1477             // send command
1478             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1479             hci_send_cmd(&hci_reset);
1480             break;
1481         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1482             hci_state_reset();
1483             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1484             hci_send_cmd(&hci_reset);
1485             break;
1486         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1487             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1488             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1489             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1490             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1491             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1492             break;
1493         }
1494         case HCI_INIT_SET_BD_ADDR:
1495             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1496             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1497             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1498             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1499             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1500             break;
1501         case HCI_INIT_SEND_BAUD_CHANGE:
1502             if (need_baud_change) {
1503                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1504                 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1505                 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1506                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1507                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1508                 // STLC25000D: baudrate change happens within 0.5 s after command was send,
1509                 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1510                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1511                     btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1512                     btstack_run_loop_add_timer(&hci_stack->timeout);
1513                }
1514                break;
1515             }
1516 
1517             /* fall through */
1518 
1519         case HCI_INIT_CUSTOM_INIT:
1520             // Custom initialization
1521             if (hci_stack->chipset && hci_stack->chipset->next_command){
1522                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1523                 bool send_cmd = false;
1524                 switch (hci_stack->chipset_result){
1525                     case BTSTACK_CHIPSET_VALID_COMMAND:
1526                         send_cmd = true;
1527                         hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1528                         break;
1529                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1530                         send_cmd = true;
1531                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1532                         log_info("CSR Warm Boot");
1533                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1534                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1535                         btstack_run_loop_add_timer(&hci_stack->timeout);
1536                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1537                             && hci_stack->config
1538                             && hci_stack->chipset
1539                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
1540                             && hci_stack->hci_transport->set_baudrate
1541                             && hci_transport_uart_get_main_baud_rate()){
1542                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1543                         } else {
1544                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1545                         }
1546                         break;
1547                     default:
1548                         break;
1549                 }
1550 
1551                 if (send_cmd){
1552                     int size = 3u + hci_stack->hci_packet_buffer[2u];
1553                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1554                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1555                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1556                     break;
1557                 }
1558                 log_info("Init script done");
1559 
1560                 // Init script download on Broadcom chipsets causes:
1561                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1562                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
1563                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
1564 
1565                     // - baud rate to reset, restore UART baud rate if needed
1566                     if (need_baud_change) {
1567                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1568                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
1569                         hci_stack->hci_transport->set_baudrate(baud_rate);
1570                     }
1571 
1572                     uint16_t bcm_delay_ms = 300;
1573                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
1574                     //   -> Work around: wait here.
1575                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
1576                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1577                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
1578                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1579                     btstack_run_loop_add_timer(&hci_stack->timeout);
1580                     break;
1581                 }
1582             }
1583             /* fall through */
1584 #endif
1585 
1586         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1587             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1588             hci_send_cmd(&hci_read_local_supported_commands);
1589             break;
1590         case HCI_INIT_READ_BD_ADDR:
1591             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1592             hci_send_cmd(&hci_read_bd_addr);
1593             break;
1594         case HCI_INIT_READ_BUFFER_SIZE:
1595             // only read buffer size if supported
1596             if (hci_stack->local_supported_commands[0u] & 0x01u) {
1597                 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1598                 hci_send_cmd(&hci_read_buffer_size);
1599                 break;
1600             }
1601             /* fall through */
1602 
1603         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1604             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1605             hci_send_cmd(&hci_read_local_supported_features);
1606             break;
1607 
1608 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1609         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
1610             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
1611             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
1612             break;
1613         case HCI_INIT_HOST_BUFFER_SIZE:
1614             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
1615             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
1616                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
1617             break;
1618 #endif
1619 
1620         case HCI_INIT_SET_EVENT_MASK:
1621             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1622             if (hci_le_supported()){
1623                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
1624             } else {
1625                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1626                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
1627             }
1628             break;
1629 
1630 #ifdef ENABLE_CLASSIC
1631         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1632             if (hci_classic_supported() && gap_ssp_supported()){
1633                 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1634                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1635                 break;
1636             }
1637             /* fall through */
1638 
1639         case HCI_INIT_WRITE_INQUIRY_MODE:
1640             if (hci_classic_supported()){
1641                 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1642                 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1643                 break;
1644             }
1645             /* fall through */
1646 
1647         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
1648             // skip write secure connections host support if not supported or disabled
1649             if (hci_classic_supported() && hci_stack->secure_connections_enable && (hci_stack->local_supported_commands[1u] & 0x02u) != 0u) {
1650                 hci_send_cmd(&hci_write_secure_connections_host_support, 1);
1651                 hci_stack->secure_connections_active = true;
1652                 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
1653                 break;
1654             }
1655             /* fall through */
1656 
1657         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1658             if (hci_classic_supported()){
1659                 hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1660                 hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1661                 break;
1662             }
1663             /* fall through */
1664 
1665 #ifdef ENABLE_SCO_OVER_HCI
1666         // only sent if ENABLE_SCO_OVER_HCI is defined
1667         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1668             // skip write synchronous flow control if not supported
1669             if (hci_classic_supported() && ((hci_stack->local_supported_commands[0] & 0x04) != 0)){
1670                 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1671                 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1672                 break;
1673             }
1674             /* fall through */
1675 
1676         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1677             // skip write default erroneous data reporting if not supported
1678             if (hci_classic_supported() && ((hci_stack->local_supported_commands[0] & 0x08) != 0)){
1679                 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1680                 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1681                 break;
1682             }
1683             /* fall through */
1684 #endif
1685 
1686 #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM)
1687         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
1688         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1689             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
1690                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1691 #ifdef ENABLE_SCO_OVER_HCI
1692                 log_info("BCM: Route SCO data via HCI transport");
1693                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1694 #endif
1695 #ifdef ENABLE_SCO_OVER_PCM
1696                 log_info("BCM: Route SCO data via PCM interface");
1697 #ifdef ENABLE_BCM_PCM_WBS
1698                 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz
1699                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
1700 #else
1701                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
1702                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
1703 #endif
1704 #endif
1705                 break;
1706             }
1707             /* fall through */
1708 #endif
1709 
1710 #ifdef ENABLE_SCO_OVER_PCM
1711         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
1712             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
1713                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
1714                 log_info("BCM: Config PCM interface for I2S");
1715 #ifdef ENABLE_BCM_PCM_WBS
1716                 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
1717                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
1718 #else
1719                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
1720                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
1721 #endif
1722                 break;
1723             }
1724             /* fall through */
1725 #endif
1726 #endif
1727 
1728 #ifdef ENABLE_BLE
1729         // LE INIT
1730         case HCI_INIT_LE_READ_BUFFER_SIZE:
1731             if (hci_le_supported()){
1732                 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1733                 hci_send_cmd(&hci_le_read_buffer_size);
1734                 break;
1735             }
1736             /* fall through */
1737 
1738         case HCI_INIT_LE_SET_EVENT_MASK:
1739             if (hci_le_supported()){
1740                 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1741                 hci_send_cmd(&hci_le_set_event_mask, 0x809FF, 0x0); // bits 0-8, 11, 19
1742                 break;
1743             }
1744             /* fall through */
1745 
1746         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1747             if (hci_le_supported()){
1748                 // LE Supported Host = 1, Simultaneous Host = 0
1749                 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1750                 hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1751                 break;
1752             }
1753             /* fall through */
1754 
1755 #endif
1756 
1757 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1758         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1759             if (hci_le_supported()){
1760                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1761                 hci_send_cmd(&hci_le_read_maximum_data_length);
1762                 break;
1763             }
1764             /* fall through */
1765 
1766         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1767             if (hci_le_supported()){
1768                 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1769                 hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1770                 break;
1771             }
1772             /* fall through */
1773 #endif
1774 
1775 #ifdef ENABLE_LE_CENTRAL
1776         case HCI_INIT_READ_WHITE_LIST_SIZE:
1777             if (hci_le_supported()){
1778                 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1779                 hci_send_cmd(&hci_le_read_white_list_size);
1780                 break;
1781             }
1782             /* fall through */
1783 
1784         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1785             if (hci_le_supported()){
1786                 hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1787                 hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
1788                 break;
1789             }
1790             /* fall through */
1791 #endif
1792 
1793         case HCI_INIT_DONE:
1794             hci_stack->substate = HCI_INIT_DONE;
1795 #ifdef ENABLE_CLASSIC
1796             // init sequence complete, check if GAP Tasks are completed
1797             if (hci_stack->gap_tasks != 0) {
1798                 hci_run_gap_tasks_classic();
1799                 break;
1800             }
1801 #endif
1802             hci_init_done();
1803             break;
1804 
1805         default:
1806             return;
1807     }
1808 }
1809 
1810 static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
1811     bool command_completed = false;
1812     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1813         uint16_t opcode = little_endian_read_16(packet,3);
1814         if (opcode == hci_stack->last_cmd_opcode){
1815             command_completed = true;
1816             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1817         } else {
1818             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1819         }
1820     }
1821 
1822     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1823         uint8_t  status = packet[2];
1824         uint16_t opcode = little_endian_read_16(packet,4);
1825         if (opcode == hci_stack->last_cmd_opcode){
1826             if (status){
1827                 command_completed = true;
1828                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1829             } else {
1830                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1831             }
1832         } else {
1833             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1834         }
1835     }
1836 #ifndef HAVE_HOST_CONTROLLER_API
1837     // Vendor == CSR
1838     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
1839         // TODO: track actual command
1840         command_completed = true;
1841     }
1842 
1843     // Vendor == Toshiba
1844     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
1845         // TODO: track actual command
1846         command_completed = true;
1847         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1848         hci_stack->num_cmd_packets = 1;
1849     }
1850 #endif
1851 
1852     return command_completed;
1853 }
1854 
1855 static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
1856 
1857     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
1858 
1859     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
1860 
1861 #ifndef HAVE_HOST_CONTROLLER_API
1862 
1863     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1864     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1865     //
1866     // HCI Reset
1867     // Timeout 100 ms
1868     // HCI Reset
1869     // Command Complete Reset
1870     // HCI Read Local Version Information
1871     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1872     // hang...
1873     //
1874     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1875     if (!command_completed
1876             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
1877             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
1878 
1879         uint16_t opcode = little_endian_read_16(packet,3);
1880         if (opcode == hci_reset.opcode){
1881             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1882             return;
1883         }
1884     }
1885 
1886     // CSR & H5
1887     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1888     if (!command_completed
1889             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
1890             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
1891 
1892         uint16_t opcode = little_endian_read_16(packet,3);
1893         if (opcode == hci_reset.opcode){
1894             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1895             return;
1896         }
1897     }
1898 
1899     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1900     // fix: Correct substate and behave as command below
1901     if (command_completed){
1902         switch (hci_stack->substate){
1903             case HCI_INIT_SEND_RESET:
1904                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1905                 break;
1906             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1907                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1908                 break;
1909             default:
1910                 break;
1911         }
1912     }
1913 
1914 #endif
1915 
1916     if (!command_completed) return;
1917 
1918     bool need_baud_change = false;
1919     bool need_addr_change = false;
1920 
1921 #ifndef HAVE_HOST_CONTROLLER_API
1922     need_baud_change = hci_stack->config
1923                         && hci_stack->chipset
1924                         && hci_stack->chipset->set_baudrate_command
1925                         && hci_stack->hci_transport->set_baudrate
1926                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1927 
1928     need_addr_change = hci_stack->custom_bd_addr_set
1929                         && hci_stack->chipset
1930                         && hci_stack->chipset->set_bd_addr_command;
1931 #endif
1932 
1933     switch(hci_stack->substate){
1934 
1935 #ifndef HAVE_HOST_CONTROLLER_API
1936         case HCI_INIT_SEND_RESET:
1937             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1938             // fix: just correct substate and behave as command below
1939 
1940             /* fall through */
1941 #endif
1942 
1943         case HCI_INIT_W4_SEND_RESET:
1944             btstack_run_loop_remove_timer(&hci_stack->timeout);
1945             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1946             return;
1947 
1948 #ifndef HAVE_HOST_CONTROLLER_API
1949         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1950             // for STLC2500D, baud rate change already happened.
1951             // for others, baud rate gets changed now
1952             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1953                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1954                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
1955                 hci_stack->hci_transport->set_baudrate(baud_rate);
1956             }
1957             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1958             return;
1959         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1960             btstack_run_loop_remove_timer(&hci_stack->timeout);
1961             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1962             return;
1963         case HCI_INIT_W4_CUSTOM_INIT:
1964             // repeat custom init
1965             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1966             return;
1967 #endif
1968 
1969         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1970             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1971               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1972                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1973                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1974                 return;
1975             }
1976             if (need_addr_change){
1977                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1978                 return;
1979             }
1980             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1981             return;
1982 #ifndef HAVE_HOST_CONTROLLER_API
1983         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1984             if (need_baud_change){
1985                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1986                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
1987                 hci_stack->hci_transport->set_baudrate(baud_rate);
1988             }
1989             if (need_addr_change){
1990                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1991                 return;
1992             }
1993             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1994             return;
1995         case HCI_INIT_W4_SET_BD_ADDR:
1996             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1997             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1998             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1999                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
2000                 return;
2001             }
2002             // skipping st warm boot
2003             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2004             return;
2005         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
2006             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2007             return;
2008 #endif
2009 
2010 #ifdef ENABLE_BLE
2011         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
2012             // skip write le host if not supported (e.g. on LE only EM9301)
2013             if (hci_stack->local_supported_commands[0u] & 0x02u) break;
2014             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
2015             return;
2016 
2017 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2018         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
2019             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
2020             if ((hci_stack->local_supported_commands[0u] & 0x30u) == 0x30u){
2021                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
2022                 return;
2023             }
2024             // explicit fall through to reduce repetitions
2025 
2026 #ifdef ENABLE_LE_CENTRAL
2027             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
2028 #else
2029             hci_stack->substate = HCI_INIT_DONE;
2030 #endif
2031             return;
2032 #endif  /* ENABLE_LE_DATA_LENGTH_EXTENSION */
2033 
2034 #endif  /* ENABLE_BLE */
2035 
2036         case HCI_INIT_DONE:
2037             // set state if we came here by fall through
2038             hci_stack->substate = HCI_INIT_DONE;
2039             return;
2040 
2041         default:
2042             break;
2043     }
2044     hci_initializing_next_state();
2045 }
2046 
2047 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
2048     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
2049     bd_addr_t bd_address;
2050     (void)memcpy(&bd_address, conn->address, 6);
2051 
2052 #ifdef ENABLE_CLASSIC
2053     // cache needed data
2054     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
2055 #endif
2056 
2057     // connection failed, remove entry
2058     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2059     btstack_memory_hci_connection_free( conn );
2060 
2061 #ifdef ENABLE_CLASSIC
2062     // notify client if dedicated bonding
2063     if (notify_dedicated_bonding_failed){
2064         log_info("hci notify_dedicated_bonding_failed");
2065         hci_emit_dedicated_bonding_result(bd_address, status);
2066     }
2067 
2068     // if authentication error, also delete link key
2069     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
2070         gap_drop_link_key_for_bd_addr(bd_address);
2071     }
2072 #else
2073     UNUSED(status);
2074 #endif
2075 }
2076 
2077 #ifdef ENABLE_CLASSIC
2078 static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
2079     // SSP Controller
2080     if (features[6] & (1 << 3)){
2081         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
2082     }
2083     // eSCO
2084     if (features[3] & (1<<7)){
2085         conn->remote_supported_features[0] |= 1;
2086     }
2087     // Extended features
2088     if (features[7] & (1<<7)){
2089         conn->remote_supported_features[0] |= 2;
2090     }
2091 }
2092 
2093 static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
2094     // SSP Host
2095     if (features[0] & (1 << 0)){
2096         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
2097     }
2098     // SC Host
2099     if (features[0] & (1 << 3)){
2100         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
2101     }
2102 }
2103 
2104 static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
2105     // SC Controller
2106     if (features[1] & (1 << 0)){
2107         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2108     }
2109 }
2110 
2111 static void hci_handle_remote_features_received(hci_connection_t * conn){
2112     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2113     log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags);
2114     if (conn->bonding_flags & BONDING_DEDICATED){
2115         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2116     }
2117 }
2118 static bool hci_remote_sc_enabled(hci_connection_t * connection){
2119     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2120     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2121 }
2122 
2123 #endif
2124 
2125 static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
2126     // handle BT initialization
2127     if (hci_stack->state == HCI_STATE_INITIALIZING) {
2128         hci_initializing_event_handler(packet, size);
2129     }
2130 
2131     // help with BT sleep
2132     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
2133         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
2134         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)) {
2135         hci_initializing_next_state();
2136     }
2137 }
2138 
2139 #ifdef ENABLE_CLASSIC
2140 static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
2141     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2142     conn->encryption_key_size = encryption_key_size;
2143 
2144     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
2145         conn->requested_security_level = LEVEL_0;
2146         hci_emit_security_level(conn->con_handle, gap_security_level_for_connection(conn));
2147         return;
2148     }
2149 
2150     // Request Authentication if not already done
2151     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
2152     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2153 }
2154 #endif
2155 
2156 static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2157     UNUSED(size);
2158 
2159     uint16_t manufacturer;
2160 #ifdef ENABLE_CLASSIC
2161     hci_con_handle_t handle;
2162     hci_connection_t * conn;
2163     uint8_t status;
2164 #endif
2165     // get num cmd packets - limit to 1 to reduce complexity
2166     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
2167 
2168     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2169     switch (opcode){
2170         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2171             if (packet[5]) break;
2172             // terminate, name 248 chars
2173             packet[6+248] = 0;
2174             log_info("local name: %s", &packet[6]);
2175             break;
2176         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
2177             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2178             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2179                 uint16_t acl_len = little_endian_read_16(packet, 6);
2180                 uint16_t sco_len = packet[8];
2181 
2182                 // determine usable ACL/SCO payload size
2183                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2184                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2185 
2186                 hci_stack->acl_packets_total_num = little_endian_read_16(packet, 9);
2187                 hci_stack->sco_packets_total_num = little_endian_read_16(packet, 11);
2188 
2189                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2190                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
2191                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2192             }
2193             break;
2194         case HCI_OPCODE_HCI_READ_RSSI:
2195             if (packet[5] == ERROR_CODE_SUCCESS){
2196                 uint8_t event[5];
2197                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2198                 event[1] = 3;
2199                 (void)memcpy(&event[2], &packet[6], 3);
2200                 hci_emit_event(event, sizeof(event), 1);
2201             }
2202             break;
2203 #ifdef ENABLE_BLE
2204         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2205             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2206             hci_stack->le_acl_packets_total_num = packet[8];
2207             // determine usable ACL payload size
2208             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
2209                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
2210             }
2211             log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
2212             break;
2213 #endif
2214 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2215         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2216             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2217             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2218             log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
2219             break;
2220 #endif
2221 #ifdef ENABLE_LE_CENTRAL
2222         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2223             hci_stack->le_whitelist_capacity = packet[6];
2224             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2225             break;
2226 #endif
2227         case HCI_OPCODE_HCI_READ_BD_ADDR:
2228             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2229             log_info("Local Address, Status: 0x%02x: Addr: %s", packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
2230 #ifdef ENABLE_CLASSIC
2231             if (hci_stack->link_key_db){
2232                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
2233             }
2234 #endif
2235             break;
2236 #ifdef ENABLE_CLASSIC
2237         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
2238             hci_emit_discoverable_enabled(hci_stack->discoverable);
2239             break;
2240         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2241             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2242                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2243                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2244                 hci_emit_event(event, sizeof(event), 1);
2245             }
2246             break;
2247 #endif
2248         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
2249             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
2250 
2251 #ifdef ENABLE_CLASSIC
2252             // determine usable ACL packet types based on host buffer size and supported features
2253             hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
2254             log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
2255 #endif
2256             // Classic/LE
2257             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2258             break;
2259         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2260             manufacturer = little_endian_read_16(packet, 10);
2261             // map Cypress to Broadcom
2262             if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2263                 log_info("Treat Cypress as Broadcom");
2264                 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2265                 little_endian_store_16(packet, 10, manufacturer);
2266             }
2267             hci_stack->manufacturer = manufacturer;
2268             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2269             break;
2270         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2271             hci_stack->local_supported_commands[0] =
2272                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+14u] & 0x80u) >> 7u) |  // bit  0 = Octet 14, bit 7 / Read Buffer Size
2273                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+24u] & 0x40u) >> 5u) |  // bit  1 = Octet 24, bit 6 / Write Le Host Supported
2274                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+10u] & 0x10u) >> 2u) |  // bit  2 = Octet 10, bit 4 / Write Synchronous Flow Control Enable
2275                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+18u] & 0x08u)     )  |  // bit  3 = Octet 18, bit 3 / Write Default Erroneous Data Reporting
2276                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+34u] & 0x01u) << 4u) |  // bit  4 = Octet 34, bit 0 / LE Write Suggested Default Data Length
2277                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x08u) << 2u) |  // bit  5 = Octet 35, bit 3 / LE Read Maximum Data Length
2278                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x20u) << 1u) |  // bit  6 = Octet 35, bit 5 / LE Set Default PHY
2279                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+20u] & 0x10u) << 3u);   // bit  7 = Octet 20, bit 4 / Read Encryption Key Size
2280             hci_stack->local_supported_commands[1] =
2281                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+ 2u] & 0x40u) >> 6u) |  // bit  8 = Octet  2, bit 6 / Read Remote Extended Features
2282                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x08u) >> 2u) |  // bit  9 = Octet 32, bit 3 / Write Secure Connections Host
2283                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x02u) << 1u) |  // bit 10 = Octet 35, bit 1 / LE Set Address Resolution Enable
2284                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x02u) << 2u) |  // bit 11 = Octet 32, bit 1 / Remote OOB Extended Data Request Reply
2285                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x40u) >> 2u);   // bit 12 = Octet 32, bit 6 / Read Local OOB Extended Data command
2286             log_info("Local supported commands summary %02x - %02x", hci_stack->local_supported_commands[0],  hci_stack->local_supported_commands[1]);
2287             break;
2288 #ifdef ENABLE_CLASSIC
2289         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2290             if (packet[5]) return;
2291             hci_stack->synchronous_flow_control_enabled = 1;
2292             break;
2293         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2294             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2295             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2296             conn   = hci_connection_for_handle(handle);
2297             if (conn != NULL) {
2298                 uint8_t key_size = 0;
2299                 if (status == 0){
2300                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
2301                     log_info("Handle %04x key Size: %u", handle, key_size);
2302                 } else {
2303                     key_size = 1;
2304                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2305                 }
2306                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2307             }
2308             break;
2309         // assert pairing complete event is emitted.
2310         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
2311         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
2312         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
2313         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
2314             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2315             // lookup connection by gap pairing addr
2316             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
2317             if (conn == NULL) break;
2318             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2319             break;
2320 
2321 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2322         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
2323         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
2324             uint8_t event[67];
2325             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
2326             event[1] = 65;
2327             (void)memset(&event[2], 0, 65);
2328             if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){
2329                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
2330                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
2331                     event[2] = 3;
2332                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
2333                 } else {
2334                     event[2] = 1;
2335                 }
2336             }
2337             hci_emit_event(event, sizeof(event), 0);
2338             break;
2339         }
2340 
2341         // note: only needed if user does not provide OOB data
2342         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
2343             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
2344             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
2345             if (conn == NULL) break;
2346             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2347             break;
2348 #endif
2349 #endif
2350         default:
2351             break;
2352     }
2353 }
2354 
2355 #ifdef ENABLE_BLE
2356 static void event_handle_le_connection_complete(const uint8_t * packet){
2357 	bd_addr_t addr;
2358 	bd_addr_type_t addr_type;
2359 	hci_connection_t * conn;
2360 
2361 	// Connection management
2362 	reverse_bd_addr(&packet[8], addr);
2363 	addr_type = (bd_addr_type_t)packet[7];
2364 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2365 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2366 
2367 #ifdef ENABLE_LE_CENTRAL
2368 	// handle error: error is reported only to the initiator -> outgoing connection
2369 	if (packet[3]){
2370 
2371 		// handle cancelled outgoing connection
2372 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2373 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2374 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2375 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2376 		    // reset state
2377             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2378             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2379 			// get outgoing connection conn struct for direct connect
2380 			conn = gap_get_outgoing_connection();
2381 		}
2382 
2383 		// outgoing le connection establishment is done
2384 		if (conn){
2385 			// remove entry
2386 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2387 			btstack_memory_hci_connection_free( conn );
2388 		}
2389 		return;
2390 	}
2391 #endif
2392 
2393 	// on success, both hosts receive connection complete event
2394 	if (packet[6] == HCI_ROLE_MASTER){
2395 #ifdef ENABLE_LE_CENTRAL
2396 		// if we're master on an le connection, it was an outgoing connection and we're done with it
2397 		// note: no hci_connection_t object exists yet for connect with whitelist
2398 		if (hci_is_le_connection_type(addr_type)){
2399 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2400 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2401 		}
2402 #endif
2403 	} else {
2404 #ifdef ENABLE_LE_PERIPHERAL
2405 		// if we're slave, it was an incoming connection, advertisements have stopped
2406 		hci_stack->le_advertisements_active = false;
2407 #endif
2408 	}
2409 
2410 	// LE connections are auto-accepted, so just create a connection if there isn't one already
2411 	if (!conn){
2412 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2413 	}
2414 
2415 	// no memory, sorry.
2416 	if (!conn){
2417 		return;
2418 	}
2419 
2420 	conn->state = OPEN;
2421 	conn->role  = packet[6];
2422 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
2423 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
2424 
2425 #ifdef ENABLE_LE_PERIPHERAL
2426 	if (packet[6] == HCI_ROLE_SLAVE){
2427 		hci_update_advertisements_enabled_for_current_roles();
2428 	}
2429 #endif
2430 
2431     // init unenhanced att bearer mtu
2432     conn->att_connection.mtu = ATT_DEFAULT_MTU;
2433     conn->att_connection.mtu_exchanged = false;
2434 
2435     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2436 
2437 	// restart timer
2438 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2439 	// btstack_run_loop_add_timer(&conn->timeout);
2440 
2441 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2442 
2443 	hci_emit_nr_connections_changed();
2444 }
2445 #endif
2446 
2447 #ifdef ENABLE_CLASSIC
2448 static bool hci_ssp_security_level_possible_for_io_cap(gap_security_level_t level, uint8_t io_cap_local, uint8_t io_cap_remote){
2449     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
2450     // LEVEL_4 is tested by l2cap
2451     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
2452     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
2453     if (level >= LEVEL_3){
2454         // MITM not possible without keyboard or display
2455         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
2456         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
2457 
2458         // MITM possible if one side has keyboard and the other has keyboard or display
2459         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
2460         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
2461 
2462         // MITM not possible if one side has only display and other side has no keyboard
2463         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
2464         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
2465     }
2466     // LEVEL 2 requires SSP, which is a given
2467     return true;
2468 }
2469 
2470 static bool btstack_is_null(uint8_t * data, uint16_t size){
2471     uint16_t i;
2472     for (i=0; i < size ; i++){
2473         if (data[i] != 0) {
2474             return false;
2475         }
2476     }
2477     return true;
2478 }
2479 
2480 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
2481     // get requested security level
2482     gap_security_level_t requested_security_level = conn->requested_security_level;
2483     if (hci_stack->gap_secure_connections_only_mode){
2484         requested_security_level = LEVEL_4;
2485     }
2486 
2487     // assess security: LEVEL 4 requires SC
2488     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
2489     if ((requested_security_level == LEVEL_4) &&
2490         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
2491         !hci_remote_sc_enabled(conn)){
2492         log_info("Level 4 required, but SC not supported -> abort");
2493         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2494         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2495         return;
2496     }
2497 
2498     // assess security based on io capabilities
2499     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
2500         // responder: fully validate io caps of both sides as well as OOB data
2501         bool security_possible = false;
2502         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
2503 
2504 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2505         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
2506         // so we merge the OOB data availability
2507         uint8_t have_oob_data = conn->io_cap_response_oob_data;
2508         if (conn->classic_oob_c_192 != NULL){
2509             have_oob_data |= 1;
2510         }
2511         if (conn->classic_oob_c_256 != NULL){
2512             have_oob_data |= 2;
2513         }
2514         // for up to Level 3, either P-192 as well as P-256 will do
2515         // if we don't support SC, then a) conn->classic_oob_c_256 will be NULL and b) remote should not report P-256 available
2516         // if remote does not SC, we should not receive P-256 data either
2517         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
2518             security_possible = true;
2519         }
2520         // for Level 4, P-256 is needed
2521         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
2522             security_possible = true;
2523         }
2524 #endif
2525 
2526         if (security_possible == false){
2527             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
2528             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2529             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2530             return;
2531         }
2532     } else {
2533         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
2534 #ifndef ENABLE_CLASSIC_PAIRING_OOB
2535 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
2536         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
2537             log_info("Level 3+ required, but no input/output -> abort");
2538             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2539             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2540             return;
2541         }
2542 #endif
2543 #endif
2544     }
2545 
2546 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
2547     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
2548         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
2549     } else {
2550         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2551     }
2552 #endif
2553 }
2554 
2555 #endif
2556 
2557 static void event_handler(uint8_t *packet, uint16_t size){
2558 
2559     uint16_t event_length = packet[1];
2560 
2561     // assert packet is complete
2562     if (size != (event_length + 2u)){
2563         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
2564         return;
2565     }
2566 
2567     bd_addr_type_t addr_type;
2568     hci_con_handle_t handle;
2569     hci_connection_t * conn;
2570     int i;
2571     int create_connection_cmd;
2572 
2573 #ifdef ENABLE_CLASSIC
2574     hci_link_type_t link_type;
2575     bd_addr_t addr;
2576 #endif
2577 
2578     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
2579 
2580     switch (hci_event_packet_get_type(packet)) {
2581 
2582         case HCI_EVENT_COMMAND_COMPLETE:
2583             handle_command_complete_event(packet, size);
2584             break;
2585 
2586         case HCI_EVENT_COMMAND_STATUS:
2587             // get num cmd packets - limit to 1 to reduce complexity
2588             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2589 
2590             // check command status to detected failed outgoing connections
2591             create_connection_cmd = 0;
2592 #ifdef ENABLE_CLASSIC
2593             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2594                 create_connection_cmd = 1;
2595             }
2596 #endif
2597 #ifdef ENABLE_LE_CENTRAL
2598             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
2599                 create_connection_cmd = 1;
2600             }
2601 #endif
2602             if (create_connection_cmd) {
2603                 uint8_t status = hci_event_command_status_get_status(packet);
2604                 addr_type = hci_stack->outgoing_addr_type;
2605                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
2606                 log_info("command status (create connection), status %x, connection %p, addr %s, type %x", status, conn, bd_addr_to_str(hci_stack->outgoing_addr), addr_type);
2607 
2608                 // reset outgoing address info
2609                 memset(hci_stack->outgoing_addr, 0, 6);
2610                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2611 
2612                 // on error
2613                 if (status != ERROR_CODE_SUCCESS){
2614 #ifdef ENABLE_LE_CENTRAL
2615                     if (hci_is_le_connection_type(addr_type)){
2616                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2617                         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2618                     }
2619 #endif
2620                     // error => outgoing connection failed
2621                     if (conn != NULL){
2622                         hci_handle_connection_failed(conn, status);
2623                     }
2624                 }
2625             }
2626 
2627 #ifdef ENABLE_CLASSIC
2628             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_inquiry)) {
2629                 uint8_t status = hci_event_command_status_get_status(packet);
2630                 log_info("command status (inquiry), status %x", status);
2631                 if (status == ERROR_CODE_SUCCESS) {
2632                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2633                 } else {
2634                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2635                 }
2636             }
2637 #endif
2638             break;
2639 
2640         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
2641             if (size < 3) return;
2642             uint16_t num_handles = packet[2];
2643             if (size != (3u + num_handles * 4u)) return;
2644             uint16_t offset = 3;
2645             for (i=0; i<num_handles;i++){
2646                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
2647                 offset += 2u;
2648                 uint16_t num_packets = little_endian_read_16(packet, offset);
2649                 offset += 2u;
2650 
2651                 conn = hci_connection_for_handle(handle);
2652                 if (!conn){
2653                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
2654                     continue;
2655                 }
2656 
2657                 if (conn->num_packets_sent >= num_packets){
2658                     conn->num_packets_sent -= num_packets;
2659                 } else {
2660                     log_error("hci_number_completed_packets, more packet slots freed then sent.");
2661                     conn->num_packets_sent = 0;
2662                 }
2663                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
2664 
2665 #ifdef ENABLE_CLASSIC
2666                 // For SCO, we do the can_send_now_check here
2667                 hci_notify_if_sco_can_send_now();
2668 #endif
2669             }
2670             break;
2671         }
2672 
2673 #ifdef ENABLE_CLASSIC
2674         case HCI_EVENT_INQUIRY_COMPLETE:
2675             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2676                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2677                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2678                 hci_emit_event(event, sizeof(event), 1);
2679             }
2680             break;
2681         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2682             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2683                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2684             }
2685             break;
2686         case HCI_EVENT_CONNECTION_REQUEST:
2687             reverse_bd_addr(&packet[2], addr);
2688             link_type = (hci_link_type_t) packet[11];
2689 
2690             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
2691             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
2692                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
2693                 bd_addr_copy(hci_stack->decline_addr, addr);
2694                 break;
2695             }
2696 
2697             if (hci_stack->gap_classic_accept_callback != NULL){
2698                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
2699                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
2700                     bd_addr_copy(hci_stack->decline_addr, addr);
2701                     break;
2702                 }
2703             }
2704 
2705             // TODO: eval COD 8-10
2706             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
2707             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
2708             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2709             if (!conn) {
2710                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2711             }
2712             if (!conn) {
2713                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
2714                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
2715                 bd_addr_copy(hci_stack->decline_addr, addr);
2716                 break;
2717             }
2718             conn->role  = HCI_ROLE_SLAVE;
2719             conn->state = RECEIVED_CONNECTION_REQUEST;
2720             // store info about eSCO
2721             if (link_type == HCI_LINK_TYPE_ESCO){
2722                 conn->remote_supported_features[0] |= 1;
2723             }
2724             hci_run();
2725             break;
2726 
2727         case HCI_EVENT_CONNECTION_COMPLETE:
2728             // Connection management
2729             reverse_bd_addr(&packet[5], addr);
2730             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2731             addr_type = BD_ADDR_TYPE_ACL;
2732             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2733             if (conn) {
2734                 if (!packet[2]){
2735                     conn->state = OPEN;
2736                     conn->con_handle = little_endian_read_16(packet, 3);
2737 
2738                     // queue get remote feature
2739                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
2740 
2741                     // queue set supervision timeout if we're master
2742                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
2743                         connectionSetAuthenticationFlags(conn, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
2744                     }
2745 
2746                     // restart timer
2747                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2748                     btstack_run_loop_add_timer(&conn->timeout);
2749 
2750                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2751 
2752                     hci_emit_nr_connections_changed();
2753                 } else {
2754                     // connection failed
2755                     hci_handle_connection_failed(conn, packet[2]);
2756                 }
2757             }
2758             break;
2759 
2760         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2761             reverse_bd_addr(&packet[5], addr);
2762             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2763             if (packet[2]){
2764                 // connection failed
2765                 break;
2766             }
2767             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2768             if (!conn) {
2769                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2770             }
2771             if (!conn) {
2772                 break;
2773             }
2774             conn->state = OPEN;
2775             conn->con_handle = little_endian_read_16(packet, 3);
2776 
2777 #ifdef ENABLE_SCO_OVER_HCI
2778             // update SCO
2779             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2780                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2781             }
2782             // trigger can send now
2783             if (hci_have_usb_transport()){
2784                 hci_stack->sco_can_send_now = true;
2785             }
2786 #endif
2787 #ifdef HAVE_SCO_TRANSPORT
2788             // configure sco transport
2789             if (hci_stack->sco_transport != NULL){
2790                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
2791                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
2792             }
2793 #endif
2794             break;
2795 
2796         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2797             handle = little_endian_read_16(packet, 3);
2798             conn = hci_connection_for_handle(handle);
2799             if (!conn) break;
2800             if (!packet[2]){
2801                 const uint8_t * features = &packet[5];
2802                 hci_handle_remote_features_page_0(conn, features);
2803 
2804                 // read extended features if possible
2805                 if (((hci_stack->local_supported_commands[1] & 1) != 0) && ((conn->remote_supported_features[0] & 2) != 0)) {
2806                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
2807                     break;
2808                 }
2809             }
2810             hci_handle_remote_features_received(conn);
2811             break;
2812 
2813         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
2814             handle = little_endian_read_16(packet, 3);
2815             conn = hci_connection_for_handle(handle);
2816             if (!conn) break;
2817             // status = ok, page = 1
2818             if (!packet[2]) {
2819                 uint8_t page_number = packet[5];
2820                 uint8_t maximum_page_number = packet[6];
2821                 const uint8_t * features = &packet[7];
2822                 bool done = false;
2823                 switch (page_number){
2824                     case 1:
2825                         hci_handle_remote_features_page_1(conn, features);
2826                         if (maximum_page_number >= 2){
2827                             // get Secure Connections (Controller) from Page 2 if available
2828                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
2829                         } else {
2830                             // otherwise, assume SC (Controller) == SC (Host)
2831                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
2832                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2833                             }
2834                             done = true;
2835                         }
2836                         break;
2837                     case 2:
2838                         hci_handle_remote_features_page_2(conn, features);
2839                         done = true;
2840                         break;
2841                     default:
2842                         break;
2843                 }
2844                 if (!done) break;
2845             }
2846             hci_handle_remote_features_received(conn);
2847             break;
2848 
2849         case HCI_EVENT_LINK_KEY_REQUEST:
2850 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
2851             hci_event_link_key_request_get_bd_addr(packet, addr);
2852             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2853             if (!conn) break;
2854 
2855             // lookup link key in db if not cached
2856             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
2857                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
2858             }
2859 
2860             // response sent by hci_run()
2861             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
2862 #endif
2863             break;
2864 
2865         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2866             hci_event_link_key_request_get_bd_addr(packet, addr);
2867             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2868             if (!conn) break;
2869 
2870             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
2871 
2872             // CVE-2020-26555: ignore NULL link key
2873             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
2874             if (btstack_is_null(&packet[8], 16)) break;
2875 
2876             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2877             // Change Connection Encryption keeps link key type
2878             if (link_key_type != CHANGED_COMBINATION_KEY){
2879                 conn->link_key_type = link_key_type;
2880             }
2881 
2882             // cache link key. link keys stored in little-endian format for legacy reasons
2883             memcpy(&conn->link_key, &packet[8], 16);
2884 
2885             // only store link key:
2886             // - if bondable enabled
2887             if (hci_stack->bondable == false) break;
2888             // - if security level sufficient
2889             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
2890             // - for SSP, also check if remote side requested bonding as well
2891             if (conn->link_key_type != COMBINATION_KEY){
2892                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2893                 if (!remote_bonding){
2894                     break;
2895                 }
2896             }
2897             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2898             break;
2899         }
2900 
2901         case HCI_EVENT_PIN_CODE_REQUEST:
2902             hci_event_pin_code_request_get_bd_addr(packet, addr);
2903             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2904             if (!conn) break;
2905 
2906             hci_pairing_started(conn, false);
2907             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
2908             if (!hci_stack->bondable ){
2909                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
2910                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
2911                 hci_run();
2912                 return;
2913             }
2914             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
2915             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
2916                 log_info("Level 4 required, but SC not supported -> abort");
2917                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
2918                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2919                 hci_run();
2920                 return;
2921             }
2922             break;
2923 
2924         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
2925             hci_event_io_capability_response_get_bd_addr(packet, addr);
2926             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2927             if (!conn) break;
2928 
2929             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
2930             hci_pairing_started(conn, true);
2931             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
2932             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
2933 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2934             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
2935 #endif
2936             break;
2937 
2938         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2939             hci_event_io_capability_response_get_bd_addr(packet, addr);
2940             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2941             if (!conn) break;
2942 
2943             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
2944             hci_connection_timestamp(conn);
2945             hci_pairing_started(conn, true);
2946             break;
2947 
2948 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2949         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
2950             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
2951             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2952             if (!conn) break;
2953 
2954             hci_connection_timestamp(conn);
2955 
2956             hci_pairing_started(conn, true);
2957 
2958             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
2959             break;
2960 #endif
2961 
2962         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2963             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
2964             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2965             if (!conn) break;
2966             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
2967                 if (hci_stack->ssp_auto_accept){
2968                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
2969                 };
2970             } else {
2971                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2972                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
2973                 // don't forward event to app
2974                 hci_run();
2975                 return;
2976             }
2977             break;
2978 
2979         case HCI_EVENT_USER_PASSKEY_REQUEST:
2980             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
2981             if (hci_stack->ssp_auto_accept){
2982                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
2983             };
2984             break;
2985 
2986         case HCI_EVENT_MODE_CHANGE:
2987             handle = hci_event_mode_change_get_handle(packet);
2988             conn = hci_connection_for_handle(handle);
2989             if (!conn) break;
2990             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2991             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2992             break;
2993 #endif
2994 
2995         case HCI_EVENT_ENCRYPTION_CHANGE:
2996             handle = hci_event_encryption_change_get_connection_handle(packet);
2997             conn = hci_connection_for_handle(handle);
2998             if (!conn) break;
2999             if (hci_event_encryption_change_get_status(packet) == 0u) {
3000                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
3001                 if (encryption_enabled){
3002                     if (hci_is_le_connection(conn)){
3003                         // For LE, we accept connection as encrypted
3004                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
3005                     }
3006 #ifdef ENABLE_CLASSIC
3007                     else {
3008 
3009                         // dedicated bonding: send result and disconnect
3010                         if (conn->bonding_flags & BONDING_DEDICATED){
3011                             conn->bonding_flags &= ~BONDING_DEDICATED;
3012                             conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
3013                             conn->bonding_status = packet[2];
3014                             break;
3015                         }
3016 
3017                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
3018                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type) != 0;
3019                         bool connected_uses_aes_ccm = encryption_enabled == 2;
3020                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
3021                             log_info("SC during pairing, but only E0 now -> abort");
3022                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3023                             break;
3024                         }
3025 
3026                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
3027                         if (connected_uses_aes_ccm){
3028                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3029                         }
3030 
3031 #ifdef ENABLE_TESTING_SUPPORT
3032                         // work around for issue with PTS dongle
3033                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3034 #endif
3035 
3036                         if ((hci_stack->local_supported_commands[0] & 0x80) != 0){
3037                             // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
3038                             conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
3039                         } else {
3040                             // if not, pretend everything is perfect
3041                             hci_handle_read_encryption_key_size_complete(conn, 16);
3042                         }
3043                     }
3044 #endif
3045                 } else {
3046                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
3047                 }
3048             }
3049 
3050             break;
3051 
3052 #ifdef ENABLE_CLASSIC
3053         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
3054             handle = hci_event_authentication_complete_get_connection_handle(packet);
3055             conn = hci_connection_for_handle(handle);
3056             if (!conn) break;
3057 
3058             // clear authentication active flag
3059             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
3060             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
3061 
3062             // authenticated only if auth status == 0
3063             if (hci_event_authentication_complete_get_status(packet) == 0){
3064                 // authenticated
3065                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3066 
3067                 // If not already encrypted, start encryption
3068                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
3069                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3070                     break;
3071                 }
3072             }
3073 
3074             // emit updated security level
3075             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
3076             break;
3077 
3078         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3079             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3080             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3081             if (!conn) break;
3082 
3083             // treat successfully paired connection as authenticated
3084             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
3085                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3086             }
3087 
3088             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
3089             break;
3090 #endif
3091 
3092         // HCI_EVENT_DISCONNECTION_COMPLETE
3093         // has been split, to first notify stack before shutting connection down
3094         // see end of function, too.
3095         case HCI_EVENT_DISCONNECTION_COMPLETE:
3096             if (packet[2]) break;   // status != 0
3097             handle = little_endian_read_16(packet, 3);
3098             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
3099             if (hci_stack->acl_fragmentation_total_size > 0u) {
3100                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3101                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
3102                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
3103                     hci_stack->acl_fragmentation_total_size = 0;
3104                     hci_stack->acl_fragmentation_pos = 0;
3105                     if (release_buffer){
3106                         hci_release_packet_buffer();
3107                     }
3108                 }
3109             }
3110 
3111             conn = hci_connection_for_handle(handle);
3112             if (!conn) break;
3113 #ifdef ENABLE_CLASSIC
3114             // pairing failed if it was ongoing
3115             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
3116 #endif
3117 
3118             // emit dedicatd bonding event
3119             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3120                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3121             }
3122 
3123             // mark connection for shutdown, stop timers, reset state
3124             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3125             hci_connection_stop_timer(conn);
3126             hci_connection_init(conn);
3127 
3128 #ifdef ENABLE_BLE
3129 #ifdef ENABLE_LE_PERIPHERAL
3130             // re-enable advertisements for le connections if active
3131             if (hci_is_le_connection(conn)){
3132                 hci_update_advertisements_enabled_for_current_roles();
3133             }
3134 #endif
3135 #endif
3136             break;
3137 
3138         case HCI_EVENT_HARDWARE_ERROR:
3139             log_error("Hardware Error: 0x%02x", packet[2]);
3140             if (hci_stack->hardware_error_callback){
3141                 (*hci_stack->hardware_error_callback)(packet[2]);
3142             } else {
3143                 // if no special requests, just reboot stack
3144                 hci_power_control_off();
3145                 hci_power_control_on();
3146             }
3147             break;
3148 
3149 #ifdef ENABLE_CLASSIC
3150         case HCI_EVENT_ROLE_CHANGE:
3151             if (packet[2]) break;   // status != 0
3152             reverse_bd_addr(&packet[3], addr);
3153             addr_type = BD_ADDR_TYPE_ACL;
3154             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3155             if (!conn) break;
3156             conn->role = packet[9];
3157             break;
3158 #endif
3159 
3160         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3161             // release packet buffer only for asynchronous transport and if there are not further fragements
3162             if (hci_transport_synchronous()) {
3163                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
3164                 return; // instead of break: to avoid re-entering hci_run()
3165             }
3166             hci_stack->acl_fragmentation_tx_active = 0;
3167             if (hci_stack->acl_fragmentation_total_size) break;
3168             hci_release_packet_buffer();
3169 
3170             // L2CAP receives this event via the hci_emit_event below
3171 
3172 #ifdef ENABLE_CLASSIC
3173             // For SCO, we do the can_send_now_check here
3174             hci_notify_if_sco_can_send_now();
3175 #endif
3176             break;
3177 
3178 #ifdef ENABLE_CLASSIC
3179         case HCI_EVENT_SCO_CAN_SEND_NOW:
3180             // For SCO, we do the can_send_now_check here
3181             hci_stack->sco_can_send_now = true;
3182             hci_notify_if_sco_can_send_now();
3183             return;
3184 
3185         // explode inquriy results for easier consumption
3186         case HCI_EVENT_INQUIRY_RESULT:
3187         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3188         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3189             gap_inquiry_explode(packet, size);
3190             break;
3191 #endif
3192 
3193 #ifdef ENABLE_BLE
3194         case HCI_EVENT_LE_META:
3195             switch (packet[2]){
3196 #ifdef ENABLE_LE_CENTRAL
3197                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
3198                     // log_info("advertising report received");
3199                     if (!hci_stack->le_scanning_enabled) break;
3200                     le_handle_advertisement_report(packet, size);
3201                     break;
3202 #endif
3203                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3204 					event_handle_le_connection_complete(packet);
3205                     break;
3206 
3207                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3208                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3209                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3210                     conn = hci_connection_for_handle(handle);
3211                     if (!conn) break;
3212                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3213                     break;
3214 
3215                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
3216                     // connection
3217                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
3218                     conn = hci_connection_for_handle(handle);
3219                     if (conn) {
3220                         // read arguments
3221                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
3222                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
3223                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
3224                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
3225 
3226                         // validate against current connection parameter range
3227                         le_connection_parameter_range_t existing_range;
3228                         gap_get_connection_parameter_range(&existing_range);
3229                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3230                         if (update_parameter){
3231                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
3232                             conn->le_conn_interval_min = le_conn_interval_min;
3233                             conn->le_conn_interval_max = le_conn_interval_max;
3234                             conn->le_conn_latency = le_conn_latency;
3235                             conn->le_supervision_timeout = le_supervision_timeout;
3236                         } else {
3237                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
3238                         }
3239                     }
3240                     break;
3241 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3242                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
3243                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
3244                     conn = hci_connection_for_handle(handle);
3245                     if (conn) {
3246                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
3247                     }
3248                     break;
3249 #endif
3250                 default:
3251                     break;
3252             }
3253             break;
3254 #endif
3255         case HCI_EVENT_VENDOR_SPECIFIC:
3256             // Vendor specific commands often create vendor specific event instead of num completed packets
3257             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
3258             switch (hci_stack->manufacturer){
3259                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
3260                     hci_stack->num_cmd_packets = 1;
3261                     break;
3262                 default:
3263                     break;
3264             }
3265             break;
3266         default:
3267             break;
3268     }
3269 
3270     handle_event_for_current_stack_state(packet, size);
3271 
3272     // notify upper stack
3273 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
3274 
3275     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
3276     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
3277 		handle = little_endian_read_16(packet, 3);
3278 		hci_connection_t * aConn = hci_connection_for_handle(handle);
3279 		// discard connection if app did not trigger a reconnect in the event handler
3280 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
3281 			hci_shutdown_connection(aConn);
3282 		}
3283     }
3284 
3285 	// execute main loop
3286 	hci_run();
3287 }
3288 
3289 #ifdef ENABLE_CLASSIC
3290 
3291 #ifdef ENABLE_SCO_OVER_HCI
3292 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
3293 static void sco_schedule_tx(hci_connection_t * conn);
3294 
3295 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
3296     log_debug("SCO TX Timeout");
3297     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
3298     hci_connection_t * conn = hci_connection_for_handle(con_handle);
3299     if (!conn) return;
3300 
3301     // trigger send
3302     conn->sco_tx_ready = 1;
3303     // extra packet if CVSD but SCO buffer is too short
3304     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
3305         conn->sco_tx_ready++;
3306     }
3307     hci_notify_if_sco_can_send_now();
3308 }
3309 
3310 
3311 #define SCO_TX_AFTER_RX_MS (6)
3312 
3313 static void sco_schedule_tx(hci_connection_t * conn){
3314 
3315     uint32_t now = btstack_run_loop_get_time_ms();
3316     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
3317     int time_delta_ms = sco_tx_ms - now;
3318 
3319     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
3320 
3321     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
3322     btstack_run_loop_remove_timer(timer);
3323     btstack_run_loop_set_timer(timer, time_delta_ms);
3324     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
3325     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
3326     btstack_run_loop_add_timer(timer);
3327 }
3328 #endif
3329 
3330 static void sco_handler(uint8_t * packet, uint16_t size){
3331     // lookup connection struct
3332     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
3333     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
3334     if (!conn) return;
3335 
3336 #ifdef ENABLE_SCO_OVER_HCI
3337     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
3338     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
3339         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
3340             packet[2] = 0x3c;
3341             memmove(&packet[3], &packet[23], 63);
3342             size = 63;
3343         }
3344     }
3345 
3346     if (hci_have_usb_transport()){
3347         // Nothing to do
3348     } else {
3349         // log_debug("sco flow %u, handle 0x%04x, packets sent %u, bytes send %u", hci_stack->synchronous_flow_control_enabled, (int) con_handle, conn->num_packets_sent, conn->num_sco_bytes_sent);
3350         if (hci_stack->synchronous_flow_control_enabled == 0){
3351             uint32_t now = btstack_run_loop_get_time_ms();
3352 
3353             if (!conn->sco_rx_valid){
3354                 // ignore first 10 packets
3355                 conn->sco_rx_count++;
3356                 // log_debug("sco rx count %u", conn->sco_rx_count);
3357                 if (conn->sco_rx_count == 10) {
3358                     // use first timestamp as is and pretent it just started
3359                     conn->sco_rx_ms = now;
3360                     conn->sco_rx_valid = 1;
3361                     conn->sco_rx_count = 0;
3362                     sco_schedule_tx(conn);
3363                 }
3364             } else {
3365                 // track expected arrival timme
3366                 conn->sco_rx_count++;
3367                 conn->sco_rx_ms += 7;
3368                 int delta = (int32_t) (now - conn->sco_rx_ms);
3369                 if (delta > 0){
3370                     conn->sco_rx_ms++;
3371                 }
3372                 // log_debug("sco rx %u", conn->sco_rx_ms);
3373                 sco_schedule_tx(conn);
3374             }
3375         }
3376     }
3377 #endif
3378 
3379     // deliver to app
3380     if (hci_stack->sco_packet_handler) {
3381         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
3382     }
3383 
3384 #ifdef HAVE_SCO_TRANSPORT
3385     // We can send one packet for each received packet
3386     conn->sco_tx_ready++;
3387     hci_notify_if_sco_can_send_now();
3388 #endif
3389 
3390 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3391     conn->num_packets_completed++;
3392     hci_stack->host_completed_packets = 1;
3393     hci_run();
3394 #endif
3395 }
3396 #endif
3397 
3398 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
3399     hci_dump_packet(packet_type, 1, packet, size);
3400     switch (packet_type) {
3401         case HCI_EVENT_PACKET:
3402             event_handler(packet, size);
3403             break;
3404         case HCI_ACL_DATA_PACKET:
3405             acl_handler(packet, size);
3406             break;
3407 #ifdef ENABLE_CLASSIC
3408         case HCI_SCO_DATA_PACKET:
3409             sco_handler(packet, size);
3410             break;
3411 #endif
3412         default:
3413             break;
3414     }
3415 }
3416 
3417 /**
3418  * @brief Add event packet handler.
3419  */
3420 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3421     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3422 }
3423 
3424 
3425 /** Register HCI packet handlers */
3426 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3427     hci_stack->acl_packet_handler = handler;
3428 }
3429 
3430 #ifdef ENABLE_CLASSIC
3431 /**
3432  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
3433  */
3434 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
3435     hci_stack->sco_packet_handler = handler;
3436 }
3437 #endif
3438 
3439 static void hci_state_reset(void){
3440     // no connections yet
3441     hci_stack->connections = NULL;
3442 
3443     // keep discoverable/connectable as this has been requested by the client(s)
3444     // hci_stack->discoverable = 0;
3445     // hci_stack->connectable = 0;
3446     // hci_stack->bondable = 1;
3447     // hci_stack->own_addr_type = 0;
3448 
3449     // buffer is free
3450     hci_stack->hci_packet_buffer_reserved = false;
3451 
3452     // no pending cmds
3453     hci_stack->decline_reason = 0;
3454 
3455     hci_stack->secure_connections_active = false;
3456 
3457 #ifdef ENABLE_CLASSIC
3458     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
3459     hci_stack->gap_tasks =
3460             GAP_TASK_SET_DEFAULT_LINK_POLICY |
3461             GAP_TASK_SET_CLASS_OF_DEVICE |
3462             GAP_TASK_SET_LOCAL_NAME |
3463             GAP_TASK_SET_EIR_DATA |
3464             GAP_TASK_WRITE_SCAN_ENABLE;
3465 #endif
3466 
3467 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3468     hci_stack->classic_read_local_oob_data = true;
3469     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
3470 #endif
3471 
3472     // LE
3473 #ifdef ENABLE_BLE
3474     memset(hci_stack->le_random_address, 0, 6);
3475     hci_stack->le_random_address_set = 0;
3476 #endif
3477 #ifdef ENABLE_LE_CENTRAL
3478     hci_stack->le_scanning_active  = false;
3479     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3480     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3481     hci_stack->le_whitelist_capacity = 0;
3482 #endif
3483 #ifdef ENABLE_LE_PERIPHERAL
3484     hci_stack->le_advertisements_active = false;
3485     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PARAMS_SET) != 0){
3486         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3487     }
3488     if (hci_stack->le_advertisements_data != NULL){
3489         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3490     }
3491 #endif
3492 }
3493 
3494 #ifdef ENABLE_CLASSIC
3495 /**
3496  * @brief Configure Bluetooth hardware control. Has to be called before power on.
3497  */
3498 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
3499     // store and open remote device db
3500     hci_stack->link_key_db = link_key_db;
3501     if (hci_stack->link_key_db) {
3502         hci_stack->link_key_db->open();
3503     }
3504 }
3505 #endif
3506 
3507 void hci_init(const hci_transport_t *transport, const void *config){
3508 
3509 #ifdef HAVE_MALLOC
3510     if (!hci_stack) {
3511         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
3512     }
3513 #else
3514     hci_stack = &hci_stack_static;
3515 #endif
3516     memset(hci_stack, 0, sizeof(hci_stack_t));
3517 
3518     // reference to use transport layer implementation
3519     hci_stack->hci_transport = transport;
3520 
3521     // reference to used config
3522     hci_stack->config = config;
3523 
3524     // setup pointer for outgoing packet buffer
3525     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
3526 
3527     // max acl payload size defined in config.h
3528     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
3529 
3530     // register packet handlers with transport
3531     transport->register_packet_handler(&packet_handler);
3532 
3533     hci_stack->state = HCI_STATE_OFF;
3534 
3535     // class of device
3536     hci_stack->class_of_device = 0x007a020c; // Smartphone
3537 
3538     // bondable by default
3539     hci_stack->bondable = 1;
3540 
3541 #ifdef ENABLE_CLASSIC
3542     // classic name
3543     hci_stack->local_name = default_classic_name;
3544 
3545     // Master slave policy
3546     hci_stack->master_slave_policy = 1;
3547 
3548     // Allow Role Switch
3549     hci_stack->allow_role_switch = 1;
3550 
3551     // Default / minimum security level = 2
3552     hci_stack->gap_security_level = LEVEL_2;
3553 
3554     // Default Security Mode 4
3555     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
3556 
3557     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3558     hci_stack->gap_required_encyrption_key_size = 7;
3559 
3560     // Link Supervision Timeout
3561     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
3562 
3563 #endif
3564 
3565     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
3566     hci_stack->ssp_enable = 1;
3567     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
3568     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
3569     hci_stack->ssp_auto_accept = 1;
3570 
3571     // Secure Connections: enable (requires support from Controller)
3572     hci_stack->secure_connections_enable = true;
3573 
3574     // voice setting - signed 16 bit pcm data with CVSD over the air
3575     hci_stack->sco_voice_setting = 0x60;
3576 
3577 #ifdef ENABLE_LE_CENTRAL
3578     // connection parameter to use for outgoing connections
3579     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3580     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3581     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3582     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3583     hci_stack->le_connection_latency      = 4;         // 4
3584     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3585     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3586     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
3587 
3588     // default LE Scanning
3589     hci_stack->le_scan_type     =   0x1; // active
3590     hci_stack->le_scan_interval = 0x1e0; // 300 ms
3591     hci_stack->le_scan_window   =  0x30; //  30 ms
3592 #endif
3593 
3594 #ifdef ENABLE_LE_PERIPHERAL
3595     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
3596 #endif
3597 
3598     // connection parameter range used to answer connection parameter update requests in l2cap
3599     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3600     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3601     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3602     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3603     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3604     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3605 
3606     hci_state_reset();
3607 }
3608 
3609 void hci_deinit(void){
3610 #ifdef HAVE_MALLOC
3611     if (hci_stack) {
3612         free(hci_stack);
3613     }
3614 #endif
3615     hci_stack = NULL;
3616 
3617 #ifdef ENABLE_CLASSIC
3618     disable_l2cap_timeouts = 0;
3619 #endif
3620 }
3621 
3622 /**
3623  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
3624  */
3625 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
3626     hci_stack->chipset = chipset_driver;
3627 
3628     // reset chipset driver - init is also called on power_up
3629     if (hci_stack->chipset && hci_stack->chipset->init){
3630         hci_stack->chipset->init(hci_stack->config);
3631     }
3632 }
3633 
3634 /**
3635  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3636  */
3637 void hci_set_control(const btstack_control_t *hardware_control){
3638     // references to used control implementation
3639     hci_stack->control = hardware_control;
3640     // init with transport config
3641     hardware_control->init(hci_stack->config);
3642 }
3643 
3644 void hci_close(void){
3645 
3646 #ifdef ENABLE_CLASSIC
3647     // close remote device db
3648     if (hci_stack->link_key_db) {
3649         hci_stack->link_key_db->close();
3650     }
3651 #endif
3652 
3653     btstack_linked_list_iterator_t lit;
3654     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
3655     while (btstack_linked_list_iterator_has_next(&lit)){
3656         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
3657         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
3658         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
3659         hci_shutdown_connection(connection);
3660     }
3661 
3662     hci_power_control(HCI_POWER_OFF);
3663 
3664 #ifdef HAVE_MALLOC
3665     free(hci_stack);
3666 #endif
3667     hci_stack = NULL;
3668 }
3669 
3670 #ifdef HAVE_SCO_TRANSPORT
3671 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3672     hci_stack->sco_transport = sco_transport;
3673     sco_transport->register_packet_handler(&packet_handler);
3674 }
3675 #endif
3676 
3677 #ifdef ENABLE_CLASSIC
3678 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3679     // validate ranage and set
3680     if (encryption_key_size < 7)  return;
3681     if (encryption_key_size > 16) return;
3682     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3683 }
3684 
3685 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
3686     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
3687         hci_stack->gap_security_mode = security_mode;
3688         return ERROR_CODE_SUCCESS;
3689     } else {
3690         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3691     }
3692 }
3693 
3694 gap_security_mode_t gap_get_security_mode(void){
3695     return hci_stack->gap_security_mode;
3696 }
3697 
3698 void gap_set_security_level(gap_security_level_t security_level){
3699     hci_stack->gap_security_level = security_level;
3700 }
3701 
3702 gap_security_level_t gap_get_security_level(void){
3703     if (hci_stack->gap_secure_connections_only_mode){
3704         return LEVEL_4;
3705     }
3706     return hci_stack->gap_security_level;
3707 }
3708 
3709 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
3710     hci_stack->gap_minimal_service_security_level = security_level;
3711 }
3712 
3713 void gap_set_secure_connections_only_mode(bool enable){
3714     hci_stack->gap_secure_connections_only_mode = enable;
3715 }
3716 
3717 bool gap_get_secure_connections_only_mode(void){
3718     return hci_stack->gap_secure_connections_only_mode;
3719 }
3720 #endif
3721 
3722 #ifdef ENABLE_CLASSIC
3723 void gap_set_class_of_device(uint32_t class_of_device){
3724     hci_stack->class_of_device = class_of_device;
3725     hci_stack->gap_tasks |= GAP_TASK_SET_CLASS_OF_DEVICE;
3726     hci_run();
3727 }
3728 
3729 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3730     hci_stack->default_link_policy_settings = default_link_policy_settings;
3731     hci_stack->gap_tasks |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
3732     hci_run();
3733 }
3734 
3735 void gap_set_allow_role_switch(bool allow_role_switch){
3736     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3737 }
3738 
3739 uint8_t hci_get_allow_role_switch(void){
3740     return  hci_stack->allow_role_switch;
3741 }
3742 
3743 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
3744     hci_stack->link_supervision_timeout = link_supervision_timeout;
3745 }
3746 
3747 void hci_disable_l2cap_timeout_check(void){
3748     disable_l2cap_timeouts = 1;
3749 }
3750 #endif
3751 
3752 #ifndef HAVE_HOST_CONTROLLER_API
3753 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3754 void hci_set_bd_addr(bd_addr_t addr){
3755     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3756     hci_stack->custom_bd_addr_set = 1;
3757 }
3758 #endif
3759 
3760 // State-Module-Driver overview
3761 // state                    module  low-level
3762 // HCI_STATE_OFF             off      close
3763 // HCI_STATE_INITIALIZING,   on       open
3764 // HCI_STATE_WORKING,        on       open
3765 // HCI_STATE_HALTING,        on       open
3766 // HCI_STATE_SLEEPING,    off/sleep   close
3767 // HCI_STATE_FALLING_ASLEEP  on       open
3768 
3769 static int hci_power_control_on(void){
3770 
3771     // power on
3772     int err = 0;
3773     if (hci_stack->control && hci_stack->control->on){
3774         err = (*hci_stack->control->on)();
3775     }
3776     if (err){
3777         log_error( "POWER_ON failed");
3778         hci_emit_hci_open_failed();
3779         return err;
3780     }
3781 
3782     // int chipset driver
3783     if (hci_stack->chipset && hci_stack->chipset->init){
3784         hci_stack->chipset->init(hci_stack->config);
3785     }
3786 
3787     // init transport
3788     if (hci_stack->hci_transport->init){
3789         hci_stack->hci_transport->init(hci_stack->config);
3790     }
3791 
3792     // open transport
3793     err = hci_stack->hci_transport->open();
3794     if (err){
3795         log_error( "HCI_INIT failed, turning Bluetooth off again");
3796         if (hci_stack->control && hci_stack->control->off){
3797             (*hci_stack->control->off)();
3798         }
3799         hci_emit_hci_open_failed();
3800         return err;
3801     }
3802     return 0;
3803 }
3804 
3805 static void hci_power_control_off(void){
3806 
3807     log_info("hci_power_control_off");
3808 
3809     // close low-level device
3810     hci_stack->hci_transport->close();
3811 
3812     log_info("hci_power_control_off - hci_transport closed");
3813 
3814     // power off
3815     if (hci_stack->control && hci_stack->control->off){
3816         (*hci_stack->control->off)();
3817     }
3818 
3819     log_info("hci_power_control_off - control closed");
3820 
3821     hci_stack->state = HCI_STATE_OFF;
3822 }
3823 
3824 static void hci_power_control_sleep(void){
3825 
3826     log_info("hci_power_control_sleep");
3827 
3828 #if 0
3829     // don't close serial port during sleep
3830 
3831     // close low-level device
3832     hci_stack->hci_transport->close(hci_stack->config);
3833 #endif
3834 
3835     // sleep mode
3836     if (hci_stack->control && hci_stack->control->sleep){
3837         (*hci_stack->control->sleep)();
3838     }
3839 
3840     hci_stack->state = HCI_STATE_SLEEPING;
3841 }
3842 
3843 static int hci_power_control_wake(void){
3844 
3845     log_info("hci_power_control_wake");
3846 
3847     // wake on
3848     if (hci_stack->control && hci_stack->control->wake){
3849         (*hci_stack->control->wake)();
3850     }
3851 
3852 #if 0
3853     // open low-level device
3854     int err = hci_stack->hci_transport->open(hci_stack->config);
3855     if (err){
3856         log_error( "HCI_INIT failed, turning Bluetooth off again");
3857         if (hci_stack->control && hci_stack->control->off){
3858             (*hci_stack->control->off)();
3859         }
3860         hci_emit_hci_open_failed();
3861         return err;
3862     }
3863 #endif
3864 
3865     return 0;
3866 }
3867 
3868 static void hci_power_transition_to_initializing(void){
3869     // set up state machine
3870     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
3871     hci_stack->hci_packet_buffer_reserved = false;
3872     hci_stack->state = HCI_STATE_INITIALIZING;
3873     hci_stack->substate = HCI_INIT_SEND_RESET;
3874 }
3875 
3876 // returns error
3877 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
3878     int err;
3879     switch (power_mode){
3880         case HCI_POWER_ON:
3881             err = hci_power_control_on();
3882             if (err != 0) {
3883                 log_error("hci_power_control_on() error %d", err);
3884                 return err;
3885             }
3886             hci_power_transition_to_initializing();
3887             break;
3888         case HCI_POWER_OFF:
3889             // do nothing
3890             break;
3891         case HCI_POWER_SLEEP:
3892             // do nothing (with SLEEP == OFF)
3893             break;
3894         default:
3895             btstack_assert(false);
3896             break;
3897     }
3898     return ERROR_CODE_SUCCESS;
3899 }
3900 
3901 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
3902     switch (power_mode){
3903         case HCI_POWER_ON:
3904             // do nothing
3905             break;
3906         case HCI_POWER_OFF:
3907             // no connections yet, just turn it off
3908             hci_power_control_off();
3909             break;
3910         case HCI_POWER_SLEEP:
3911             // no connections yet, just turn it off
3912             hci_power_control_sleep();
3913             break;
3914         default:
3915             btstack_assert(false);
3916             break;
3917     }
3918     return ERROR_CODE_SUCCESS;
3919 }
3920 
3921 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
3922     switch (power_mode){
3923         case HCI_POWER_ON:
3924             // do nothing
3925             break;
3926         case HCI_POWER_OFF:
3927             // see hci_run
3928             hci_stack->state = HCI_STATE_HALTING;
3929             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3930             break;
3931         case HCI_POWER_SLEEP:
3932             // see hci_run
3933             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3934             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3935             break;
3936         default:
3937             btstack_assert(false);
3938             break;
3939     }
3940     return ERROR_CODE_SUCCESS;
3941 }
3942 
3943 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
3944     switch (power_mode){
3945         case HCI_POWER_ON:
3946             hci_power_transition_to_initializing();
3947             break;
3948         case HCI_POWER_OFF:
3949             // do nothing
3950             break;
3951         case HCI_POWER_SLEEP:
3952             // see hci_run
3953             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3954             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3955             break;
3956         default:
3957             btstack_assert(false);
3958             break;
3959     }
3960     return ERROR_CODE_SUCCESS;
3961 }
3962 
3963 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
3964     switch (power_mode){
3965         case HCI_POWER_ON:
3966             hci_power_transition_to_initializing();
3967             break;
3968         case HCI_POWER_OFF:
3969             // see hci_run
3970             hci_stack->state = HCI_STATE_HALTING;
3971             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3972             break;
3973         case HCI_POWER_SLEEP:
3974             // do nothing
3975             break;
3976         default:
3977             btstack_assert(false);
3978             break;
3979     }
3980     return ERROR_CODE_SUCCESS;
3981 }
3982 
3983 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
3984     int err;
3985     switch (power_mode){
3986         case HCI_POWER_ON:
3987             err = hci_power_control_wake();
3988             if (err) return err;
3989             hci_power_transition_to_initializing();
3990             break;
3991         case HCI_POWER_OFF:
3992             hci_stack->state = HCI_STATE_HALTING;
3993             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3994             break;
3995         case HCI_POWER_SLEEP:
3996             // do nothing
3997             break;
3998         default:
3999             btstack_assert(false);
4000             break;
4001     }
4002     return ERROR_CODE_SUCCESS;
4003 }
4004 
4005 int hci_power_control(HCI_POWER_MODE power_mode){
4006     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
4007     int err = 0;
4008     switch (hci_stack->state){
4009         case HCI_STATE_OFF:
4010             err = hci_power_control_state_off(power_mode);
4011             break;
4012         case HCI_STATE_INITIALIZING:
4013             err = hci_power_control_state_initializing(power_mode);
4014             break;
4015         case HCI_STATE_WORKING:
4016             err = hci_power_control_state_working(power_mode);
4017             break;
4018         case HCI_STATE_HALTING:
4019             err = hci_power_control_state_halting(power_mode);
4020             break;
4021         case HCI_STATE_FALLING_ASLEEP:
4022             err = hci_power_control_state_falling_asleep(power_mode);
4023             break;
4024         case HCI_STATE_SLEEPING:
4025             err = hci_power_control_state_sleeping(power_mode);
4026             break;
4027         default:
4028             btstack_assert(false);
4029             break;
4030     }
4031     if (err != 0){
4032         return err;
4033     }
4034 
4035     // create internal event
4036 	hci_emit_state();
4037 
4038 	// trigger next/first action
4039 	hci_run();
4040 
4041     return 0;
4042 }
4043 
4044 
4045 #ifdef ENABLE_CLASSIC
4046 
4047 static void hci_update_scan_enable(void){
4048     // 2 = page scan, 1 = inq scan
4049     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
4050     hci_stack->gap_tasks |= GAP_TASK_WRITE_SCAN_ENABLE;
4051     hci_run();
4052 }
4053 
4054 void gap_discoverable_control(uint8_t enable){
4055     if (enable) enable = 1; // normalize argument
4056 
4057     if (hci_stack->discoverable == enable){
4058         hci_emit_discoverable_enabled(hci_stack->discoverable);
4059         return;
4060     }
4061 
4062     hci_stack->discoverable = enable;
4063     hci_update_scan_enable();
4064 }
4065 
4066 void gap_connectable_control(uint8_t enable){
4067     if (enable) enable = 1; // normalize argument
4068 
4069     // don't emit event
4070     if (hci_stack->connectable == enable) return;
4071 
4072     hci_stack->connectable = enable;
4073     hci_update_scan_enable();
4074 }
4075 #endif
4076 
4077 void gap_local_bd_addr(bd_addr_t address_buffer){
4078     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
4079 }
4080 
4081 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4082 static void hci_host_num_completed_packets(void){
4083 
4084     // create packet manually as arrays are not supported and num_commands should not get reduced
4085     hci_reserve_packet_buffer();
4086     uint8_t * packet = hci_get_outgoing_packet_buffer();
4087 
4088     uint16_t size = 0;
4089     uint16_t num_handles = 0;
4090     packet[size++] = 0x35;
4091     packet[size++] = 0x0c;
4092     size++;  // skip param len
4093     size++;  // skip num handles
4094 
4095     // add { handle, packets } entries
4096     btstack_linked_item_t * it;
4097     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4098         hci_connection_t * connection = (hci_connection_t *) it;
4099         if (connection->num_packets_completed){
4100             little_endian_store_16(packet, size, connection->con_handle);
4101             size += 2;
4102             little_endian_store_16(packet, size, connection->num_packets_completed);
4103             size += 2;
4104             //
4105             num_handles++;
4106             connection->num_packets_completed = 0;
4107         }
4108     }
4109 
4110     packet[2] = size - 3;
4111     packet[3] = num_handles;
4112 
4113     hci_stack->host_completed_packets = 0;
4114 
4115     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4116     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
4117 
4118     // release packet buffer for synchronous transport implementations
4119     if (hci_transport_synchronous()){
4120         hci_release_packet_buffer();
4121         hci_emit_transport_packet_sent();
4122     }
4123 }
4124 #endif
4125 
4126 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
4127     UNUSED(ds);
4128     hci_stack->substate = HCI_HALTING_CLOSE;
4129     // allow packet handlers to defer final shutdown
4130     hci_emit_state();
4131     hci_run();
4132 }
4133 
4134 static bool hci_run_acl_fragments(void){
4135     if (hci_stack->acl_fragmentation_total_size > 0u) {
4136         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
4137         hci_connection_t *connection = hci_connection_for_handle(con_handle);
4138         if (connection) {
4139             if (hci_can_send_prepared_acl_packet_now(con_handle)){
4140                 hci_send_acl_packet_fragments(connection);
4141                 return true;
4142             }
4143         } else {
4144             // connection gone -> discard further fragments
4145             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
4146             hci_stack->acl_fragmentation_total_size = 0;
4147             hci_stack->acl_fragmentation_pos = 0;
4148         }
4149     }
4150     return false;
4151 }
4152 
4153 #ifdef ENABLE_CLASSIC
4154 static bool hci_run_general_gap_classic(void){
4155 
4156     // assert stack is working and classic is active
4157     if (hci_classic_supported() == false)      return false;
4158     if (hci_stack->state != HCI_STATE_WORKING) return false;
4159 
4160     // decline incoming connections
4161     if (hci_stack->decline_reason){
4162         uint8_t reason = hci_stack->decline_reason;
4163         hci_stack->decline_reason = 0;
4164         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
4165         return true;
4166     }
4167 
4168     if (hci_stack->gap_tasks != 0){
4169         hci_run_gap_tasks_classic();
4170         return true;
4171     }
4172 
4173     // start/stop inquiry
4174     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
4175         uint8_t duration = hci_stack->inquiry_state;
4176         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
4177         hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
4178         return true;
4179     }
4180     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
4181         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
4182         hci_send_cmd(&hci_inquiry_cancel);
4183         return true;
4184     }
4185     // remote name request
4186     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
4187         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
4188         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
4189                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
4190         return true;
4191     }
4192 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4193     // Local OOB data
4194     if (hci_stack->classic_read_local_oob_data){
4195         hci_stack->classic_read_local_oob_data = false;
4196         if (hci_stack->local_supported_commands[1] & 0x10u){
4197             hci_send_cmd(&hci_read_local_extended_oob_data);
4198         } else {
4199             hci_send_cmd(&hci_read_local_oob_data);
4200         }
4201     }
4202 #endif
4203     // pairing
4204     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
4205         uint8_t state = hci_stack->gap_pairing_state;
4206         uint8_t pin_code[16];
4207         switch (state){
4208             case GAP_PAIRING_STATE_SEND_PIN:
4209                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4210                 memset(pin_code, 0, 16);
4211                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
4212                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
4213                 break;
4214             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
4215                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4216                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
4217                 break;
4218             case GAP_PAIRING_STATE_SEND_PASSKEY:
4219                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4220                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
4221                 break;
4222             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
4223                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4224                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
4225                 break;
4226             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
4227                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4228                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
4229                 break;
4230             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
4231                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4232                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
4233                 break;
4234             default:
4235                 break;
4236         }
4237         return true;
4238     }
4239     return false;
4240 }
4241 #endif
4242 
4243 #ifdef ENABLE_BLE
4244 static bool hci_run_general_gap_le(void){
4245 
4246     // advertisements, active scanning, and creating connections requires random address to be set if using private address
4247 
4248     if (hci_stack->state != HCI_STATE_WORKING) return false;
4249     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
4250 
4251 
4252     // Phase 1: collect what to stop
4253 
4254     bool scanning_stop = false;
4255     bool connecting_stop = false;
4256     bool advertising_stop = false;
4257 
4258 #ifndef ENABLE_LE_CENTRAL
4259     UNUSED(scanning_stop);
4260     UNUSED(connecting_stop);
4261 #endif
4262 #ifndef ENABLE_LE_PERIPHERAL
4263     UNUSED(advertising_stop);
4264 #endif
4265 
4266     // check if whitelist needs modification
4267     bool whitelist_modification_pending = false;
4268     btstack_linked_list_iterator_t lit;
4269     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4270     while (btstack_linked_list_iterator_has_next(&lit)){
4271         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4272         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
4273             whitelist_modification_pending = true;
4274             break;
4275         }
4276     }
4277     // check if resolving list needs modification
4278     bool resolving_list_modification_pending = false;
4279 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4280     bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0;
4281 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
4282         resolving_list_modification_pending = true;
4283     }
4284 #endif
4285 
4286 #ifdef ENABLE_LE_CENTRAL
4287     // scanning control
4288     if (hci_stack->le_scanning_active) {
4289         // stop if:
4290         // - parameter change required
4291         // - it's disabled
4292         // - whitelist change required but used for scanning
4293         // - resolving list modified
4294         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
4295         if ((hci_stack->le_scanning_param_update) ||
4296             !hci_stack->le_scanning_enabled ||
4297             scanning_uses_whitelist ||
4298             resolving_list_modification_pending){
4299 
4300             scanning_stop = true;
4301         }
4302     }
4303 #endif
4304 
4305 #ifdef ENABLE_LE_CENTRAL
4306     // connecting control
4307     bool connecting_with_whitelist;
4308     switch (hci_stack->le_connecting_state){
4309         case LE_CONNECTING_DIRECT:
4310         case LE_CONNECTING_WHITELIST:
4311             // stop connecting if:
4312             // - connecting uses white and whitelist modification pending
4313             // - if it got disabled
4314             // - resolving list modified
4315             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
4316             if ((connecting_with_whitelist && whitelist_modification_pending) ||
4317                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
4318                 resolving_list_modification_pending) {
4319 
4320                 connecting_stop = true;
4321             }
4322             break;
4323         default:
4324             break;
4325     }
4326 #endif
4327 
4328 #ifdef ENABLE_LE_PERIPHERAL
4329     // le advertisement control
4330     if (hci_stack->le_advertisements_active){
4331         // stop if:
4332         // - parameter change required
4333         // - it's disabled
4334         // - whitelist change required but used for advertisement filter policy
4335         // - resolving list modified
4336         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
4337         bool advertising_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
4338         if (advertising_change ||
4339             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
4340             (advertising_uses_whitelist & whitelist_modification_pending) ||
4341             resolving_list_modification_pending) {
4342 
4343             advertising_stop = true;
4344         }
4345     }
4346 #endif
4347 
4348 
4349     // Phase 2: stop everything that should be off during modifications
4350 
4351 #ifdef ENABLE_LE_CENTRAL
4352     if (scanning_stop){
4353         hci_stack->le_scanning_active = false;
4354         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
4355         return true;
4356     }
4357 #endif
4358 
4359 #ifdef ENABLE_LE_CENTRAL
4360     if (connecting_stop){
4361         hci_send_cmd(&hci_le_create_connection_cancel);
4362         return true;
4363     }
4364 #endif
4365 
4366 #ifdef ENABLE_LE_PERIPHERAL
4367     if (advertising_stop){
4368         hci_stack->le_advertisements_active = false;
4369         hci_send_cmd(&hci_le_set_advertise_enable, 0);
4370         return true;
4371     }
4372 #endif
4373 
4374     // Phase 3: modify
4375 
4376 #ifdef ENABLE_LE_CENTRAL
4377     if (hci_stack->le_scanning_param_update){
4378         hci_stack->le_scanning_param_update = false;
4379         hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
4380                      hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
4381         return true;
4382     }
4383 #endif
4384 
4385 #ifdef ENABLE_LE_PERIPHERAL
4386     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
4387         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4388         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
4389         hci_send_cmd(&hci_le_set_advertising_parameters,
4390                      hci_stack->le_advertisements_interval_min,
4391                      hci_stack->le_advertisements_interval_max,
4392                      hci_stack->le_advertisements_type,
4393                      hci_stack->le_advertisements_own_addr_type,
4394                      hci_stack->le_advertisements_direct_address_type,
4395                      hci_stack->le_advertisements_direct_address,
4396                      hci_stack->le_advertisements_channel_map,
4397                      hci_stack->le_advertisements_filter_policy);
4398         return true;
4399     }
4400     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
4401         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4402         uint8_t adv_data_clean[31];
4403         memset(adv_data_clean, 0, sizeof(adv_data_clean));
4404         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
4405                      hci_stack->le_advertisements_data_len);
4406         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
4407         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
4408         return true;
4409     }
4410     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
4411         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4412         uint8_t scan_data_clean[31];
4413         memset(scan_data_clean, 0, sizeof(scan_data_clean));
4414         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
4415                      hci_stack->le_scan_response_data_len);
4416         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
4417         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
4418         return true;
4419     }
4420 #endif
4421 
4422 
4423 #ifdef ENABLE_LE_CENTRAL
4424     // if connect with whitelist was active and is not cancelled yet, wait until next time
4425     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
4426 #endif
4427 
4428     // LE Whitelist Management
4429     if (whitelist_modification_pending){
4430         // add/remove entries
4431         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4432         while (btstack_linked_list_iterator_has_next(&lit)){
4433             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4434 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
4435 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4436 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
4437 				return true;
4438 			}
4439             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
4440 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
4441                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
4442                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
4443                 return true;
4444             }
4445             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
4446 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
4447 				btstack_memory_whitelist_entry_free(entry);
4448             }
4449         }
4450     }
4451 
4452 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4453     // LE Resolving List Management
4454     if (resolving_list_supported) {
4455 		uint16_t i;
4456 		switch (hci_stack->le_resolving_list_state) {
4457 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
4458 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
4459 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
4460 				return true;
4461 			case LE_RESOLVING_LIST_READ_SIZE:
4462 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
4463 				hci_send_cmd(&hci_le_read_resolving_list_size);
4464 				return true;
4465 			case LE_RESOLVING_LIST_SEND_CLEAR:
4466 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
4467 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
4468 							  sizeof(hci_stack->le_resolving_list_add_entries));
4469 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
4470 							  sizeof(hci_stack->le_resolving_list_remove_entries));
4471 				hci_send_cmd(&hci_le_clear_resolving_list);
4472 				return true;
4473 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
4474 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4475 					uint8_t offset = i >> 3;
4476 					uint8_t mask = 1 << (i & 7);
4477 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
4478 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
4479 					bd_addr_t peer_identity_addreses;
4480 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4481 					sm_key_t peer_irk;
4482 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4483 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4484 
4485 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
4486 					// trigger whitelist entry 'update' (work around for controller bug)
4487 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4488 					while (btstack_linked_list_iterator_has_next(&lit)) {
4489 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
4490 						if (entry->address_type != peer_identity_addr_type) continue;
4491 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
4492 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
4493 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
4494 					}
4495 #endif
4496 
4497 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
4498 								 peer_identity_addreses);
4499 					return true;
4500 				}
4501 
4502 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
4503 
4504 				/* fall through */
4505 
4506 			case LE_RESOLVING_LIST_ADD_ENTRIES:
4507 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4508 					uint8_t offset = i >> 3;
4509 					uint8_t mask = 1 << (i & 7);
4510 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
4511 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
4512 					bd_addr_t peer_identity_addreses;
4513 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4514 					sm_key_t peer_irk;
4515 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4516 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4517 					const uint8_t *local_irk = gap_get_persistent_irk();
4518 					// command uses format specifier 'P' that stores 16-byte value without flip
4519 					uint8_t local_irk_flipped[16];
4520 					uint8_t peer_irk_flipped[16];
4521 					reverse_128(local_irk, local_irk_flipped);
4522 					reverse_128(peer_irk, peer_irk_flipped);
4523 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
4524 								 peer_irk_flipped, local_irk_flipped);
4525 					return true;
4526 				}
4527 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4528 				break;
4529 
4530 			default:
4531 				break;
4532 		}
4533 	}
4534     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4535 #endif
4536 
4537     // Phase 4: restore state
4538 
4539 #ifdef ENABLE_LE_CENTRAL
4540     // re-start scanning
4541     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
4542         hci_stack->le_scanning_active = true;
4543         hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
4544         return true;
4545     }
4546 #endif
4547 
4548 #ifdef ENABLE_LE_CENTRAL
4549     // re-start connecting
4550     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
4551         bd_addr_t null_addr;
4552         memset(null_addr, 0, 6);
4553         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
4554         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
4555         hci_send_cmd(&hci_le_create_connection,
4556                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
4557                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
4558                      1,         // use whitelist
4559                      0,         // peer address type
4560                      null_addr, // peer bd addr
4561                      hci_stack->le_connection_own_addr_type,   // our addr type:
4562                      hci_stack->le_connection_interval_min,    // conn interval min
4563                      hci_stack->le_connection_interval_max,    // conn interval max
4564                      hci_stack->le_connection_latency,         // conn latency
4565                      hci_stack->le_supervision_timeout,        // conn latency
4566                      hci_stack->le_minimum_ce_length,          // min ce length
4567                      hci_stack->le_maximum_ce_length           // max ce length
4568         );
4569         return true;
4570     }
4571 #endif
4572 
4573 #ifdef ENABLE_LE_PERIPHERAL
4574     // re-start advertising
4575     if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){
4576         // check if advertisements should be enabled given
4577         hci_stack->le_advertisements_active = true;
4578         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
4579         hci_send_cmd(&hci_le_set_advertise_enable, 1);
4580         return true;
4581     }
4582 #endif
4583 
4584     return false;
4585 }
4586 #endif
4587 
4588 static bool hci_run_general_pending_commands(void){
4589     btstack_linked_item_t * it;
4590     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
4591         hci_connection_t * connection = (hci_connection_t *) it;
4592 
4593         switch(connection->state){
4594             case SEND_CREATE_CONNECTION:
4595                 switch(connection->address_type){
4596 #ifdef ENABLE_CLASSIC
4597                     case BD_ADDR_TYPE_ACL:
4598                         log_info("sending hci_create_connection");
4599                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
4600                         break;
4601 #endif
4602                     default:
4603 #ifdef ENABLE_BLE
4604 #ifdef ENABLE_LE_CENTRAL
4605                         log_info("sending hci_le_create_connection");
4606                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
4607                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
4608                         hci_send_cmd(&hci_le_create_connection,
4609                                      hci_stack->le_connection_scan_interval,    // conn scan interval
4610                                      hci_stack->le_connection_scan_window,      // conn scan windows
4611                                      0,         // don't use whitelist
4612                                      connection->address_type, // peer address type
4613                                      connection->address,      // peer bd addr
4614                                      hci_stack->le_connection_own_addr_type,   // our addr type:
4615                                      hci_stack->le_connection_interval_min,    // conn interval min
4616                                      hci_stack->le_connection_interval_max,    // conn interval max
4617                                      hci_stack->le_connection_latency,         // conn latency
4618                                      hci_stack->le_supervision_timeout,        // conn latency
4619                                      hci_stack->le_minimum_ce_length,          // min ce length
4620                                      hci_stack->le_maximum_ce_length          // max ce length
4621                         );
4622                         connection->state = SENT_CREATE_CONNECTION;
4623 #endif
4624 #endif
4625                         break;
4626                 }
4627                 return true;
4628 
4629 #ifdef ENABLE_CLASSIC
4630             case RECEIVED_CONNECTION_REQUEST:
4631                 connection->role  = HCI_ROLE_SLAVE;
4632                 if (connection->address_type == BD_ADDR_TYPE_ACL){
4633                     log_info("sending hci_accept_connection_request");
4634                     connection->state = ACCEPTED_CONNECTION_REQUEST;
4635                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
4636                 }
4637                 return true;
4638 #endif
4639 
4640 #ifdef ENABLE_BLE
4641 #ifdef ENABLE_LE_CENTRAL
4642             case SEND_CANCEL_CONNECTION:
4643                 connection->state = SENT_CANCEL_CONNECTION;
4644                 hci_send_cmd(&hci_le_create_connection_cancel);
4645                 return true;
4646 #endif
4647 #endif
4648             case SEND_DISCONNECT:
4649                 connection->state = SENT_DISCONNECT;
4650                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4651                 return true;
4652 
4653             default:
4654                 break;
4655         }
4656 
4657         // no further commands if connection is about to get shut down
4658         if (connection->state == SENT_DISCONNECT) continue;
4659 
4660         if (connection->authentication_flags & AUTH_FLAG_READ_RSSI){
4661             connectionClearAuthenticationFlags(connection, AUTH_FLAG_READ_RSSI);
4662             hci_send_cmd(&hci_read_rssi, connection->con_handle);
4663             return true;
4664         }
4665 
4666 #ifdef ENABLE_CLASSIC
4667 
4668         if (connection->authentication_flags & AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT){
4669             connectionClearAuthenticationFlags(connection, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
4670             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
4671             return true;
4672         }
4673 
4674         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
4675             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
4676             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
4677             return true;
4678         }
4679 
4680         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
4681             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
4682             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
4683             return true;
4684         }
4685 
4686         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
4687             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
4688             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
4689             return true;
4690         }
4691 
4692         // Handling link key request requires remote supported features
4693         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
4694             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
4695             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
4696 
4697             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
4698             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
4699             if (have_link_key && security_level_sufficient){
4700                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
4701             } else {
4702                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
4703             }
4704             return true;
4705         }
4706 
4707         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
4708             log_info("denying to pin request");
4709             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
4710             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
4711             return true;
4712         }
4713 
4714         // security assessment requires remote features
4715         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
4716             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
4717             hci_ssp_assess_security_on_io_cap_request(connection);
4718             // no return here as hci_ssp_assess_security_on_io_cap_request only sets AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY or AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY
4719         }
4720 
4721         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
4722             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
4723             // set authentication requirements:
4724             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
4725             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
4726             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
4727             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
4728                 authreq |= 1;
4729             }
4730             bool bonding = hci_stack->bondable;
4731             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
4732                 // if we have received IO Cap Response, we're in responder role
4733                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4734                 if (bonding && !remote_bonding){
4735                     log_info("Remote not bonding, dropping local flag");
4736                     bonding = false;
4737                 }
4738             }
4739             if (bonding){
4740                 if (connection->bonding_flags & BONDING_DEDICATED){
4741                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4742                 } else {
4743                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4744                 }
4745             }
4746             uint8_t have_oob_data = 0;
4747 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4748             if (connection->classic_oob_c_192 != NULL){
4749                     have_oob_data |= 1;
4750             }
4751             if (connection->classic_oob_c_256 != NULL){
4752                 have_oob_data |= 2;
4753             }
4754 #endif
4755             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
4756             return true;
4757         }
4758 
4759         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
4760             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
4761             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
4762             return true;
4763         }
4764 
4765 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4766         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
4767             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
4768             const uint8_t zero[16] = { 0 };
4769             const uint8_t * r_192 = zero;
4770             const uint8_t * c_192 = zero;
4771             const uint8_t * r_256 = zero;
4772             const uint8_t * c_256 = zero;
4773             // verify P-256 OOB
4774             if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) {
4775                 c_256 = connection->classic_oob_c_256;
4776                 if (connection->classic_oob_r_256 != NULL) {
4777                     r_256 = connection->classic_oob_r_256;
4778                 }
4779             }
4780             // verify P-192 OOB
4781             if ((connection->classic_oob_c_192 != NULL)) {
4782                 c_192 = connection->classic_oob_c_192;
4783                 if (connection->classic_oob_r_192 != NULL) {
4784                     r_192 = connection->classic_oob_r_192;
4785                 }
4786             }
4787 
4788             // assess security
4789             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
4790             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
4791             if (need_level_4 && !can_reach_level_4){
4792                 log_info("Level 4 required, but not possible -> abort");
4793                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
4794                 // send oob negative reply
4795                 c_256 = NULL;
4796                 c_192 = NULL;
4797             }
4798 
4799             // Reply
4800             if (c_256 != zero) {
4801                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
4802             } else if (c_192 != zero){
4803                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
4804             } else {
4805                 hci_stack->classic_oob_con_handle = connection->con_handle;
4806                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
4807             }
4808             return true;
4809         }
4810 #endif
4811 
4812         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
4813             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4814             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
4815             return true;
4816         }
4817 
4818         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
4819             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4820             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
4821             return true;
4822         }
4823 
4824         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
4825             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4826             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
4827             return true;
4828         }
4829 
4830         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
4831             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
4832             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
4833             connection->state = SENT_DISCONNECT;
4834             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4835             return true;
4836         }
4837 
4838         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
4839             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
4840             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
4841             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
4842             return true;
4843         }
4844 
4845         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
4846             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
4847             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
4848             return true;
4849         }
4850         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
4851             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4852             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
4853             return true;
4854         }
4855 #endif
4856 
4857         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
4858             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
4859 #ifdef ENABLE_CLASSIC
4860             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
4861 #endif
4862             if (connection->state != SENT_DISCONNECT){
4863                 connection->state = SENT_DISCONNECT;
4864                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4865                 return true;
4866             }
4867         }
4868 
4869 #ifdef ENABLE_CLASSIC
4870         uint16_t sniff_min_interval;
4871         switch (connection->sniff_min_interval){
4872             case 0:
4873                 break;
4874             case 0xffff:
4875                 connection->sniff_min_interval = 0;
4876                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
4877                 return true;
4878             default:
4879                 sniff_min_interval = connection->sniff_min_interval;
4880                 connection->sniff_min_interval = 0;
4881                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
4882                 return true;
4883         }
4884 
4885         if (connection->sniff_subrating_max_latency != 0xffff){
4886             uint16_t max_latency = connection->sniff_subrating_max_latency;
4887             connection->sniff_subrating_max_latency = 0;
4888             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
4889             return true;
4890         }
4891 
4892         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
4893             uint8_t service_type = (uint8_t) connection->qos_service_type;
4894             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
4895             hci_send_cmd(&hci_qos_setup, connection->con_handle, 0, service_type, connection->qos_token_rate, connection->qos_peak_bandwidth, connection->qos_latency, connection->qos_delay_variation);
4896             return true;
4897         }
4898 
4899         if (connection->request_role != HCI_ROLE_INVALID){
4900             hci_role_t role = connection->request_role;
4901             connection->request_role = HCI_ROLE_INVALID;
4902             hci_send_cmd(&hci_switch_role_command, connection->address, role);
4903             return true;
4904         }
4905 #endif
4906 
4907 #ifdef ENABLE_BLE
4908         switch (connection->le_con_parameter_update_state){
4909             // response to L2CAP CON PARAMETER UPDATE REQUEST
4910             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
4911                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4912                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
4913                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4914                              0x0000, 0xffff);
4915                 return true;
4916             case CON_PARAMETER_UPDATE_REPLY:
4917                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4918                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
4919                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4920                              0x0000, 0xffff);
4921                 return true;
4922             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
4923                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4924                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
4925                 return true;
4926             default:
4927                 break;
4928         }
4929         if (connection->le_phy_update_all_phys != 0xffu){
4930             uint8_t all_phys = connection->le_phy_update_all_phys;
4931             connection->le_phy_update_all_phys = 0xff;
4932             hci_send_cmd(&hci_le_set_phy, connection->con_handle, all_phys, connection->le_phy_update_tx_phys, connection->le_phy_update_rx_phys, connection->le_phy_update_phy_options);
4933             return true;
4934         }
4935 #endif
4936     }
4937     return false;
4938 }
4939 
4940 static void hci_run(void){
4941 
4942     bool done;
4943 
4944     // send continuation fragments first, as they block the prepared packet buffer
4945     done = hci_run_acl_fragments();
4946     if (done) return;
4947 
4948 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4949     // send host num completed packets next as they don't require num_cmd_packets > 0
4950     if (!hci_can_send_comand_packet_transport()) return;
4951     if (hci_stack->host_completed_packets){
4952         hci_host_num_completed_packets();
4953         return;
4954     }
4955 #endif
4956 
4957     if (!hci_can_send_command_packet_now()) return;
4958 
4959     // global/non-connection oriented commands
4960 
4961 
4962 #ifdef ENABLE_CLASSIC
4963     // general gap classic
4964     done = hci_run_general_gap_classic();
4965     if (done) return;
4966 #endif
4967 
4968 #ifdef ENABLE_BLE
4969     // general gap le
4970     done = hci_run_general_gap_le();
4971     if (done) return;
4972 #endif
4973 
4974     // send pending HCI commands
4975     done = hci_run_general_pending_commands();
4976     if (done) return;
4977 
4978     // stack state sub statemachines
4979     hci_connection_t * connection;
4980     switch (hci_stack->state){
4981         case HCI_STATE_INITIALIZING:
4982             hci_initializing_run();
4983             break;
4984 
4985         case HCI_STATE_HALTING:
4986 
4987             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4988             switch (hci_stack->substate){
4989                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
4990                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
4991 
4992 #ifdef ENABLE_BLE
4993 #ifdef ENABLE_LE_CENTRAL
4994                     // free whitelist entries
4995                     {
4996                         btstack_linked_list_iterator_t lit;
4997                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4998                         while (btstack_linked_list_iterator_has_next(&lit)){
4999                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5000                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5001                             btstack_memory_whitelist_entry_free(entry);
5002                         }
5003                     }
5004 #endif
5005 #endif
5006                     // close all open connections
5007                     connection =  (hci_connection_t *) hci_stack->connections;
5008                     if (connection){
5009                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5010                         if (!hci_can_send_command_packet_now()) return;
5011 
5012                         // check state
5013                         if (connection->state == SENT_DISCONNECT) return;
5014                         connection->state = SENT_DISCONNECT;
5015 
5016                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
5017 
5018                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
5019                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
5020 
5021                         // ... which would be ignored anyway as we shutdown (free) the connection now
5022                         hci_shutdown_connection(connection);
5023 
5024                         // finally, send the disconnect command
5025                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5026                         return;
5027                     }
5028 
5029                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
5030                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5031                         log_info("HCI_STATE_HALTING: wait 50 ms");
5032                         hci_stack->substate = HCI_HALTING_W4_TIMER;
5033                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5034                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5035                         btstack_run_loop_add_timer(&hci_stack->timeout);
5036                         break;
5037                     }
5038 
5039                     /* fall through */
5040 
5041                 case HCI_HALTING_CLOSE:
5042                     log_info("HCI_STATE_HALTING, calling off");
5043 
5044                     // switch mode
5045                     hci_power_control_off();
5046 
5047                     log_info("HCI_STATE_HALTING, emitting state");
5048                     hci_emit_state();
5049                     log_info("HCI_STATE_HALTING, done");
5050                     break;
5051 
5052                 case HCI_HALTING_W4_TIMER:
5053                     // keep waiting
5054 
5055                     break;
5056                 default:
5057                     break;
5058             }
5059 
5060             break;
5061 
5062         case HCI_STATE_FALLING_ASLEEP:
5063             switch(hci_stack->substate) {
5064                 case HCI_FALLING_ASLEEP_DISCONNECT:
5065                     log_info("HCI_STATE_FALLING_ASLEEP");
5066                     // close all open connections
5067                     connection =  (hci_connection_t *) hci_stack->connections;
5068                     if (connection){
5069 
5070                         // send disconnect
5071                         if (!hci_can_send_command_packet_now()) return;
5072 
5073                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5074                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5075 
5076                         // send disconnected event right away - causes higher layer connections to get closed, too.
5077                         hci_shutdown_connection(connection);
5078                         return;
5079                     }
5080 
5081                     if (hci_classic_supported()){
5082                         // disable page and inquiry scan
5083                         if (!hci_can_send_command_packet_now()) return;
5084 
5085                         log_info("HCI_STATE_HALTING, disabling inq scans");
5086                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5087 
5088                         // continue in next sub state
5089                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5090                         break;
5091                     }
5092 
5093                     /* fall through */
5094 
5095                 case HCI_FALLING_ASLEEP_COMPLETE:
5096                     log_info("HCI_STATE_HALTING, calling sleep");
5097                     // switch mode
5098                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5099                     hci_emit_state();
5100                     break;
5101 
5102                 default:
5103                     break;
5104             }
5105             break;
5106 
5107         default:
5108             break;
5109     }
5110 }
5111 
5112 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
5113     // house-keeping
5114 
5115 #ifdef ENABLE_CLASSIC
5116     bd_addr_t addr;
5117     hci_connection_t * conn;
5118 #endif
5119 #ifdef ENABLE_LE_CENTRAL
5120     uint8_t initiator_filter_policy;
5121 #endif
5122 
5123     uint16_t opcode = little_endian_read_16(packet, 0);
5124     switch (opcode) {
5125         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
5126             hci_stack->loopback_mode = packet[3];
5127             break;
5128 
5129 #ifdef ENABLE_CLASSIC
5130         case HCI_OPCODE_HCI_CREATE_CONNECTION:
5131             reverse_bd_addr(&packet[3], addr);
5132             log_info("Create_connection to %s", bd_addr_to_str(addr));
5133 
5134             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
5135             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
5136                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
5137                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
5138             }
5139 
5140             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5141             if (!conn) {
5142                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5143                 if (!conn) {
5144                     // notify client that alloc failed
5145                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5146                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
5147                 }
5148                 conn->state = SEND_CREATE_CONNECTION;
5149                 conn->role  = HCI_ROLE_MASTER;
5150             }
5151 
5152             conn->con_handle = HCI_CON_HANDLE_INVALID;
5153             conn->role = HCI_ROLE_INVALID;
5154 
5155             log_info("conn state %u", conn->state);
5156             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
5157             switch (conn->state) {
5158                 // if connection active exists
5159                 case OPEN:
5160                     // and OPEN, emit connection complete command
5161                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
5162                     // packet not sent to controller
5163                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5164                 case RECEIVED_DISCONNECTION_COMPLETE:
5165                     // create connection triggered in disconnect complete event, let's do it now
5166                     break;
5167                 case SEND_CREATE_CONNECTION:
5168                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
5169                     break;
5170                 default:
5171                     // otherwise, just ignore as it is already in the open process
5172                     // packet not sent to controller
5173                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5174             }
5175             conn->state = SENT_CREATE_CONNECTION;
5176 
5177             // track outgoing connection
5178             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
5179             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
5180             break;
5181         case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY:
5182             if (hci_stack->link_key_db) {
5183                 reverse_bd_addr(&packet[3], addr);
5184                 hci_stack->link_key_db->delete_link_key(addr);
5185             }
5186             break;
5187 
5188 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
5189         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
5190             // setup_synchronous_connection? Voice setting at offset 22
5191             // TODO: compare to current setting if sco connection already active
5192             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
5193             break;
5194         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
5195             // accept_synchronus_connection? Voice setting at offset 18
5196             // TODO: compare to current setting if sco connection already active
5197             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
5198             break;
5199 #endif
5200 #endif
5201 
5202 #ifdef ENABLE_BLE
5203         case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS:
5204             hci_stack->le_random_address_set = 1;
5205             reverse_bd_addr(&packet[3], hci_stack->le_random_address);
5206             break;
5207 #ifdef ENABLE_LE_PERIPHERAL
5208         case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE:
5209             hci_stack->le_advertisements_active = packet[3] != 0;
5210             break;
5211 #endif
5212 #ifdef ENABLE_LE_CENTRAL
5213         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
5214             // white list used?
5215             initiator_filter_policy = packet[7];
5216             switch (initiator_filter_policy) {
5217                 case 0:
5218                     // whitelist not used
5219                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
5220                     break;
5221                 case 1:
5222                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
5223                     break;
5224                 default:
5225                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
5226                     break;
5227             }
5228             // track outgoing connection
5229             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
5230             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
5231             break;
5232         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
5233             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
5234             break;
5235 #endif
5236 #endif
5237         default:
5238             break;
5239     }
5240 
5241     hci_stack->num_cmd_packets--;
5242 
5243     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5244     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5245     if (err != 0){
5246         return ERROR_CODE_HARDWARE_FAILURE;
5247     }
5248     return ERROR_CODE_SUCCESS;
5249 }
5250 
5251 // disconnect because of security block
5252 void hci_disconnect_security_block(hci_con_handle_t con_handle){
5253     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5254     if (!connection) return;
5255     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
5256 }
5257 
5258 
5259 // Configure Secure Simple Pairing
5260 
5261 #ifdef ENABLE_CLASSIC
5262 
5263 // enable will enable SSP during init
5264 void gap_ssp_set_enable(int enable){
5265     hci_stack->ssp_enable = enable;
5266 }
5267 
5268 static int hci_local_ssp_activated(void){
5269     return gap_ssp_supported() && hci_stack->ssp_enable;
5270 }
5271 
5272 // if set, BTstack will respond to io capability request using authentication requirement
5273 void gap_ssp_set_io_capability(int io_capability){
5274     hci_stack->ssp_io_capability = io_capability;
5275 }
5276 void gap_ssp_set_authentication_requirement(int authentication_requirement){
5277     hci_stack->ssp_authentication_requirement = authentication_requirement;
5278 }
5279 
5280 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
5281 void gap_ssp_set_auto_accept(int auto_accept){
5282     hci_stack->ssp_auto_accept = auto_accept;
5283 }
5284 
5285 void gap_secure_connections_enable(bool enable){
5286     hci_stack->secure_connections_enable = enable;
5287 }
5288 
5289 #endif
5290 
5291 // va_list part of hci_send_cmd
5292 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
5293     if (!hci_can_send_command_packet_now()){
5294         log_error("hci_send_cmd called but cannot send packet now");
5295         return ERROR_CODE_COMMAND_DISALLOWED;
5296     }
5297 
5298     // for HCI INITIALIZATION
5299     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
5300     hci_stack->last_cmd_opcode = cmd->opcode;
5301 
5302     hci_reserve_packet_buffer();
5303     uint8_t * packet = hci_stack->hci_packet_buffer;
5304     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
5305     uint8_t status = hci_send_cmd_packet(packet, size);
5306 
5307     // release packet buffer on error or for synchronous transport implementations
5308     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
5309         hci_release_packet_buffer();
5310         hci_emit_transport_packet_sent();
5311     }
5312 
5313     return status;
5314 }
5315 
5316 /**
5317  * pre: numcmds >= 0 - it's allowed to send a command to the controller
5318  */
5319 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
5320     va_list argptr;
5321     va_start(argptr, cmd);
5322     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
5323     va_end(argptr);
5324     return status;
5325 }
5326 
5327 // Create various non-HCI events.
5328 // TODO: generalize, use table similar to hci_create_command
5329 
5330 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
5331     // dump packet
5332     if (dump) {
5333         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
5334     }
5335 
5336     // dispatch to all event handlers
5337     btstack_linked_list_iterator_t it;
5338     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
5339     while (btstack_linked_list_iterator_has_next(&it)){
5340         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
5341         entry->callback(HCI_EVENT_PACKET, 0, event, size);
5342     }
5343 }
5344 
5345 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
5346     if (!hci_stack->acl_packet_handler) return;
5347     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
5348 }
5349 
5350 #ifdef ENABLE_CLASSIC
5351 static void hci_notify_if_sco_can_send_now(void){
5352     // notify SCO sender if waiting
5353     if (!hci_stack->sco_waiting_for_can_send_now) return;
5354     if (hci_can_send_sco_packet_now()){
5355         hci_stack->sco_waiting_for_can_send_now = 0;
5356         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
5357         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
5358         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
5359     }
5360 }
5361 
5362 // parsing end emitting has been merged to reduce code size
5363 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
5364     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
5365 
5366     uint8_t * eir_data;
5367     ad_context_t context;
5368     const uint8_t * name;
5369     uint8_t         name_len;
5370 
5371     if (size < 3) return;
5372 
5373     int event_type = hci_event_packet_get_type(packet);
5374     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
5375     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
5376 
5377     switch (event_type){
5378         case HCI_EVENT_INQUIRY_RESULT:
5379         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5380             if (size != (3 + (num_responses * 14))) return;
5381             break;
5382         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5383             if (size != 257) return;
5384             if (num_responses != 1) return;
5385             break;
5386         default:
5387             return;
5388     }
5389 
5390     // event[1] is set at the end
5391     int i;
5392     for (i=0; i<num_responses;i++){
5393         memset(event, 0, sizeof(event));
5394         event[0] = GAP_EVENT_INQUIRY_RESULT;
5395         uint8_t event_size = 27;    // if name is not set by EIR
5396 
5397         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
5398         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
5399         (void)memcpy(&event[9],
5400                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
5401                      3); // class of device
5402         (void)memcpy(&event[12],
5403                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
5404                      2); // clock offset
5405 
5406         switch (event_type){
5407             case HCI_EVENT_INQUIRY_RESULT:
5408                 // 14,15,16,17 = 0, size 18
5409                 break;
5410             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5411                 event[14] = 1;
5412                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5413                 // 16,17 = 0, size 18
5414                 break;
5415             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5416                 event[14] = 1;
5417                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5418                 // EIR packets only contain a single inquiry response
5419                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
5420                 name = NULL;
5421                 // Iterate over EIR data
5422                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
5423                     uint8_t data_type    = ad_iterator_get_data_type(&context);
5424                     uint8_t data_size    = ad_iterator_get_data_len(&context);
5425                     const uint8_t * data = ad_iterator_get_data(&context);
5426                     // Prefer Complete Local Name over Shortened Local Name
5427                     switch (data_type){
5428                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
5429                             if (name) continue;
5430                             /* fall through */
5431                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
5432                             name = data;
5433                             name_len = data_size;
5434                             break;
5435                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
5436                             if (data_size != 8) break;
5437                             event[16] = 1;
5438                             memcpy(&event[17], data, 8);
5439                             break;
5440                         default:
5441                             break;
5442                     }
5443                 }
5444                 if (name){
5445                     event[25] = 1;
5446                     // truncate name if needed
5447                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
5448                     event[26] = len;
5449                     (void)memcpy(&event[27], name, len);
5450                     event_size += len;
5451                 }
5452                 break;
5453             default:
5454                 return;
5455         }
5456         event[1] = event_size - 2;
5457         hci_emit_event(event, event_size, 1);
5458     }
5459 }
5460 #endif
5461 
5462 void hci_emit_state(void){
5463     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
5464     uint8_t event[3];
5465     event[0] = BTSTACK_EVENT_STATE;
5466     event[1] = sizeof(event) - 2u;
5467     event[2] = hci_stack->state;
5468     hci_emit_event(event, sizeof(event), 1);
5469 }
5470 
5471 #ifdef ENABLE_CLASSIC
5472 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5473     uint8_t event[13];
5474     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
5475     event[1] = sizeof(event) - 2;
5476     event[2] = status;
5477     little_endian_store_16(event, 3, con_handle);
5478     reverse_bd_addr(address, &event[5]);
5479     event[11] = 1; // ACL connection
5480     event[12] = 0; // encryption disabled
5481     hci_emit_event(event, sizeof(event), 1);
5482 }
5483 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
5484     if (disable_l2cap_timeouts) return;
5485     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
5486     uint8_t event[4];
5487     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
5488     event[1] = sizeof(event) - 2;
5489     little_endian_store_16(event, 2, conn->con_handle);
5490     hci_emit_event(event, sizeof(event), 1);
5491 }
5492 #endif
5493 
5494 #ifdef ENABLE_BLE
5495 #ifdef ENABLE_LE_CENTRAL
5496 static void hci_emit_le_connection_complete(uint8_t address_type, const bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5497     uint8_t event[21];
5498     event[0] = HCI_EVENT_LE_META;
5499     event[1] = sizeof(event) - 2u;
5500     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
5501     event[3] = status;
5502     little_endian_store_16(event, 4, con_handle);
5503     event[6] = 0; // TODO: role
5504     event[7] = address_type;
5505     reverse_bd_addr(address, &event[8]);
5506     little_endian_store_16(event, 14, 0); // interval
5507     little_endian_store_16(event, 16, 0); // latency
5508     little_endian_store_16(event, 18, 0); // supervision timeout
5509     event[20] = 0; // master clock accuracy
5510     hci_emit_event(event, sizeof(event), 1);
5511 }
5512 #endif
5513 #endif
5514 
5515 static void hci_emit_transport_packet_sent(void){
5516     // notify upper stack that it might be possible to send again
5517     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
5518     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
5519 }
5520 
5521 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
5522     uint8_t event[6];
5523     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
5524     event[1] = sizeof(event) - 2u;
5525     event[2] = 0; // status = OK
5526     little_endian_store_16(event, 3, con_handle);
5527     event[5] = reason;
5528     hci_emit_event(event, sizeof(event), 1);
5529 }
5530 
5531 static void hci_emit_nr_connections_changed(void){
5532     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
5533     uint8_t event[3];
5534     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
5535     event[1] = sizeof(event) - 2u;
5536     event[2] = nr_hci_connections();
5537     hci_emit_event(event, sizeof(event), 1);
5538 }
5539 
5540 static void hci_emit_hci_open_failed(void){
5541     log_info("BTSTACK_EVENT_POWERON_FAILED");
5542     uint8_t event[2];
5543     event[0] = BTSTACK_EVENT_POWERON_FAILED;
5544     event[1] = sizeof(event) - 2u;
5545     hci_emit_event(event, sizeof(event), 1);
5546 }
5547 
5548 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
5549     log_info("hci_emit_dedicated_bonding_result %u ", status);
5550     uint8_t event[9];
5551     int pos = 0;
5552     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
5553     event[pos++] = sizeof(event) - 2u;
5554     event[pos++] = status;
5555     reverse_bd_addr(address, &event[pos]);
5556     hci_emit_event(event, sizeof(event), 1);
5557 }
5558 
5559 
5560 #ifdef ENABLE_CLASSIC
5561 
5562 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
5563     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
5564     uint8_t event[5];
5565     int pos = 0;
5566     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
5567     event[pos++] = sizeof(event) - 2;
5568     little_endian_store_16(event, 2, con_handle);
5569     pos += 2;
5570     event[pos++] = level;
5571     hci_emit_event(event, sizeof(event), 1);
5572 }
5573 
5574 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
5575     if (!connection) return LEVEL_0;
5576     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
5577     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
5578     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
5579     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
5580     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
5581     // LEVEL 4 always requires 128 bit encrytion key size
5582     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
5583         security_level = LEVEL_3;
5584     }
5585     return security_level;
5586 }
5587 
5588 static void hci_emit_discoverable_enabled(uint8_t enabled){
5589     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
5590     uint8_t event[3];
5591     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
5592     event[1] = sizeof(event) - 2;
5593     event[2] = enabled;
5594     hci_emit_event(event, sizeof(event), 1);
5595 }
5596 
5597 // query if remote side supports eSCO
5598 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
5599     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5600     if (!connection) return false;
5601     return (connection->remote_supported_features[0] & 1) != 0;
5602 }
5603 
5604 static bool hci_ssp_supported(hci_connection_t * connection){
5605     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
5606     return (connection->bonding_flags & mask) == mask;
5607 }
5608 
5609 // query if remote side supports SSP
5610 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
5611     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5612     if (!connection) return false;
5613     return hci_ssp_supported(connection) ? 1 : 0;
5614 }
5615 
5616 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
5617     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
5618 }
5619 
5620 // GAP API
5621 /**
5622  * @bbrief enable/disable bonding. default is enabled
5623  * @praram enabled
5624  */
5625 void gap_set_bondable_mode(int enable){
5626     hci_stack->bondable = enable ? 1 : 0;
5627 }
5628 /**
5629  * @brief Get bondable mode.
5630  * @return 1 if bondable
5631  */
5632 int gap_get_bondable_mode(void){
5633     return hci_stack->bondable;
5634 }
5635 
5636 /**
5637  * @brief map link keys to security levels
5638  */
5639 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
5640     switch (link_key_type){
5641         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5642             return LEVEL_4;
5643         case COMBINATION_KEY:
5644         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5645             return LEVEL_3;
5646         default:
5647             return LEVEL_2;
5648     }
5649 }
5650 
5651 /**
5652  * @brief map link keys to secure connection yes/no
5653  */
5654 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
5655     switch (link_key_type){
5656         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5657         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5658             return 1;
5659         default:
5660             return 0;
5661     }
5662 }
5663 
5664 /**
5665  * @brief map link keys to authenticated
5666  */
5667 int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
5668     switch (link_key_type){
5669         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5670         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5671             return 1;
5672         default:
5673             return 0;
5674     }
5675 }
5676 
5677 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
5678     log_info("gap_mitm_protection_required_for_security_level %u", level);
5679     return level > LEVEL_2;
5680 }
5681 
5682 /**
5683  * @brief get current security level
5684  */
5685 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
5686     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5687     if (!connection) return LEVEL_0;
5688     return gap_security_level_for_connection(connection);
5689 }
5690 
5691 /**
5692  * @brief request connection to device to
5693  * @result GAP_AUTHENTICATION_RESULT
5694  */
5695 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
5696     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5697     if (!connection){
5698         hci_emit_security_level(con_handle, LEVEL_0);
5699         return;
5700     }
5701 
5702     btstack_assert(hci_is_le_connection(connection) == false);
5703 
5704     // Core Spec 5.2, GAP 5.2.2: "When in Secure Connections Only mode, all services (except those allowed to have Security Mode 4, Level 0)
5705     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
5706     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
5707         requested_level = LEVEL_4;
5708     }
5709 
5710     gap_security_level_t current_level = gap_security_level(con_handle);
5711     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
5712         requested_level, connection->requested_security_level, current_level);
5713 
5714     // authentication active if authentication request was sent or planned level > 0
5715     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
5716     if (authentication_active){
5717         // authentication already active
5718         if (connection->requested_security_level < requested_level){
5719             // increase requested level as new level is higher
5720             // TODO: handle re-authentication when done
5721             connection->requested_security_level = requested_level;
5722         }
5723     } else {
5724         // no request active, notify if security sufficient
5725         if (requested_level <= current_level){
5726             hci_emit_security_level(con_handle, current_level);
5727             return;
5728         }
5729 
5730         // store request
5731         connection->requested_security_level = requested_level;
5732 
5733         // start to authenticate connection
5734         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
5735         hci_run();
5736     }
5737 }
5738 
5739 /**
5740  * @brief start dedicated bonding with device. disconnect after bonding
5741  * @param device
5742  * @param request MITM protection
5743  * @result GAP_DEDICATED_BONDING_COMPLETE
5744  */
5745 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
5746 
5747     // create connection state machine
5748     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
5749 
5750     if (!connection){
5751         return BTSTACK_MEMORY_ALLOC_FAILED;
5752     }
5753 
5754     // delete linkn key
5755     gap_drop_link_key_for_bd_addr(device);
5756 
5757     // configure LEVEL_2/3, dedicated bonding
5758     connection->state = SEND_CREATE_CONNECTION;
5759     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
5760     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
5761     connection->bonding_flags = BONDING_DEDICATED;
5762 
5763     // wait for GAP Security Result and send GAP Dedicated Bonding complete
5764 
5765     // handle: connnection failure (connection complete != ok)
5766     // handle: authentication failure
5767     // handle: disconnect on done
5768 
5769     hci_run();
5770 
5771     return 0;
5772 }
5773 
5774 void gap_set_local_name(const char * local_name){
5775     hci_stack->local_name = local_name;
5776     hci_stack->gap_tasks |= GAP_TASK_SET_LOCAL_NAME;
5777     // also update EIR if not set by user
5778     if (hci_stack->eir_data == NULL){
5779         hci_stack->gap_tasks |= GAP_TASK_SET_EIR_DATA;
5780     }
5781     hci_run();
5782 }
5783 #endif
5784 
5785 
5786 #ifdef ENABLE_BLE
5787 
5788 #ifdef ENABLE_LE_CENTRAL
5789 void gap_start_scan(void){
5790     hci_stack->le_scanning_enabled = true;
5791     hci_run();
5792 }
5793 
5794 void gap_stop_scan(void){
5795     hci_stack->le_scanning_enabled = false;
5796     hci_run();
5797 }
5798 
5799 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
5800     hci_stack->le_scan_type          = scan_type;
5801     hci_stack->le_scan_filter_policy = scanning_filter_policy;
5802     hci_stack->le_scan_interval      = scan_interval;
5803     hci_stack->le_scan_window        = scan_window;
5804     hci_stack->le_scanning_param_update = true;
5805     hci_run();
5806 }
5807 
5808 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
5809     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
5810 }
5811 
5812 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
5813     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
5814     if (!conn){
5815         // disallow if le connection is already outgoing
5816         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5817             log_error("le connection already active");
5818             return ERROR_CODE_COMMAND_DISALLOWED;
5819         }
5820 
5821         log_info("gap_connect: no connection exists yet, creating context");
5822         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
5823         if (!conn){
5824             // notify client that alloc failed
5825             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5826             log_info("gap_connect: failed to alloc hci_connection_t");
5827             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
5828         }
5829 
5830         // set le connecting state
5831         if (hci_is_le_connection_type(addr_type)){
5832             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
5833         }
5834 
5835         conn->state = SEND_CREATE_CONNECTION;
5836         log_info("gap_connect: send create connection next");
5837         hci_run();
5838         return ERROR_CODE_SUCCESS;
5839     }
5840 
5841     if (!hci_is_le_connection(conn) ||
5842         (conn->state == SEND_CREATE_CONNECTION) ||
5843         (conn->state == SENT_CREATE_CONNECTION)) {
5844         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
5845         log_error("gap_connect: classic connection or connect is already being created");
5846         return GATT_CLIENT_IN_WRONG_STATE;
5847     }
5848 
5849     // check if connection was just disconnected
5850     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5851         log_info("gap_connect: send create connection (again)");
5852         conn->state = SEND_CREATE_CONNECTION;
5853         hci_run();
5854         return ERROR_CODE_SUCCESS;
5855     }
5856 
5857     log_info("gap_connect: context exists with state %u", conn->state);
5858     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
5859     hci_run();
5860     return ERROR_CODE_SUCCESS;
5861 }
5862 
5863 // @assumption: only a single outgoing LE Connection exists
5864 static hci_connection_t * gap_get_outgoing_connection(void){
5865     btstack_linked_item_t *it;
5866     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5867         hci_connection_t * conn = (hci_connection_t *) it;
5868         if (!hci_is_le_connection(conn)) continue;
5869         switch (conn->state){
5870             case SEND_CREATE_CONNECTION:
5871             case SENT_CREATE_CONNECTION:
5872             case SENT_CANCEL_CONNECTION:
5873                 return conn;
5874             default:
5875                 break;
5876         };
5877     }
5878     return NULL;
5879 }
5880 
5881 uint8_t gap_connect_cancel(void){
5882     hci_connection_t * conn = gap_get_outgoing_connection();
5883     if (!conn) return 0;
5884     switch (conn->state){
5885         case SEND_CREATE_CONNECTION:
5886             // skip sending create connection and emit event instead
5887             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
5888             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
5889             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
5890             btstack_memory_hci_connection_free( conn );
5891             break;
5892         case SENT_CREATE_CONNECTION:
5893             // request to send cancel connection
5894             conn->state = SEND_CANCEL_CONNECTION;
5895             hci_run();
5896             break;
5897         default:
5898             break;
5899     }
5900     return 0;
5901 }
5902 #endif
5903 
5904 #ifdef ENABLE_LE_CENTRAL
5905 /**
5906  * @brief Set connection parameters for outgoing connections
5907  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
5908  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
5909  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
5910  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
5911  * @param conn_latency, default: 4
5912  * @param supervision_timeout (unit: 10ms), default: 720 ms
5913  * @param min_ce_length (unit: 0.625ms), default: 10 ms
5914  * @param max_ce_length (unit: 0.625ms), default: 30 ms
5915  */
5916 
5917 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
5918     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
5919     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
5920     hci_stack->le_connection_scan_interval = conn_scan_interval;
5921     hci_stack->le_connection_scan_window = conn_scan_window;
5922     hci_stack->le_connection_interval_min = conn_interval_min;
5923     hci_stack->le_connection_interval_max = conn_interval_max;
5924     hci_stack->le_connection_latency = conn_latency;
5925     hci_stack->le_supervision_timeout = supervision_timeout;
5926     hci_stack->le_minimum_ce_length = min_ce_length;
5927     hci_stack->le_maximum_ce_length = max_ce_length;
5928 }
5929 #endif
5930 
5931 /**
5932  * @brief Updates the connection parameters for a given LE connection
5933  * @param handle
5934  * @param conn_interval_min (unit: 1.25ms)
5935  * @param conn_interval_max (unit: 1.25ms)
5936  * @param conn_latency
5937  * @param supervision_timeout (unit: 10ms)
5938  * @returns 0 if ok
5939  */
5940 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5941     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5942     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5943     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5944     connection->le_conn_interval_min = conn_interval_min;
5945     connection->le_conn_interval_max = conn_interval_max;
5946     connection->le_conn_latency = conn_latency;
5947     connection->le_supervision_timeout = supervision_timeout;
5948     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
5949     hci_run();
5950     return 0;
5951 }
5952 
5953 /**
5954  * @brief Request an update of the connection parameter for a given LE connection
5955  * @param handle
5956  * @param conn_interval_min (unit: 1.25ms)
5957  * @param conn_interval_max (unit: 1.25ms)
5958  * @param conn_latency
5959  * @param supervision_timeout (unit: 10ms)
5960  * @returns 0 if ok
5961  */
5962 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5963     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5964     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5965     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5966     connection->le_conn_interval_min = conn_interval_min;
5967     connection->le_conn_interval_max = conn_interval_max;
5968     connection->le_conn_latency = conn_latency;
5969     connection->le_supervision_timeout = supervision_timeout;
5970     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
5971     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
5972     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
5973     return 0;
5974 }
5975 
5976 #ifdef ENABLE_LE_PERIPHERAL
5977 
5978 /**
5979  * @brief Set Advertisement Data
5980  * @param advertising_data_length
5981  * @param advertising_data (max 31 octets)
5982  * @note data is not copied, pointer has to stay valid
5983  */
5984 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
5985     hci_stack->le_advertisements_data_len = advertising_data_length;
5986     hci_stack->le_advertisements_data = advertising_data;
5987     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5988     hci_run();
5989 }
5990 
5991 /**
5992  * @brief Set Scan Response Data
5993  * @param advertising_data_length
5994  * @param advertising_data (max 31 octets)
5995  * @note data is not copied, pointer has to stay valid
5996  */
5997 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
5998     hci_stack->le_scan_response_data_len = scan_response_data_length;
5999     hci_stack->le_scan_response_data = scan_response_data;
6000     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6001     hci_run();
6002 }
6003 
6004 /**
6005  * @brief Set Advertisement Parameters
6006  * @param adv_int_min
6007  * @param adv_int_max
6008  * @param adv_type
6009  * @param direct_address_type
6010  * @param direct_address
6011  * @param channel_map
6012  * @param filter_policy
6013  *
6014  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
6015  */
6016  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
6017     uint8_t direct_address_typ, bd_addr_t direct_address,
6018     uint8_t channel_map, uint8_t filter_policy) {
6019 
6020     hci_stack->le_advertisements_interval_min = adv_int_min;
6021     hci_stack->le_advertisements_interval_max = adv_int_max;
6022     hci_stack->le_advertisements_type = adv_type;
6023     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
6024     hci_stack->le_advertisements_channel_map = channel_map;
6025     hci_stack->le_advertisements_filter_policy = filter_policy;
6026     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
6027                  6);
6028 
6029     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS | LE_ADVERTISEMENT_TASKS_PARAMS_SET;
6030     hci_run();
6031  }
6032 
6033 /**
6034  * @brief Enable/Disable Advertisements
6035  * @param enabled
6036  */
6037 void gap_advertisements_enable(int enabled){
6038     hci_stack->le_advertisements_enabled = enabled != 0;
6039     hci_update_advertisements_enabled_for_current_roles();
6040     hci_run();
6041 }
6042 
6043 #endif
6044 
6045 void hci_le_set_own_address_type(uint8_t own_address_type){
6046     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
6047     if (own_address_type == hci_stack->le_own_addr_type) return;
6048     hci_stack->le_own_addr_type = own_address_type;
6049 
6050 #ifdef ENABLE_LE_PERIPHERAL
6051     // update advertisement parameters, too
6052     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6053     hci_run();
6054 #endif
6055 #ifdef ENABLE_LE_CENTRAL
6056     // note: we don't update scan parameters or modify ongoing connection attempts
6057 #endif
6058 }
6059 
6060 #endif
6061 
6062 uint8_t gap_disconnect(hci_con_handle_t handle){
6063     hci_connection_t * conn = hci_connection_for_handle(handle);
6064     if (!conn){
6065         hci_emit_disconnection_complete(handle, 0);
6066         return 0;
6067     }
6068     // ignore if already disconnected
6069     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
6070         return 0;
6071     }
6072     conn->state = SEND_DISCONNECT;
6073     hci_run();
6074     return 0;
6075 }
6076 
6077 int gap_read_rssi(hci_con_handle_t con_handle){
6078     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6079     if (hci_connection == NULL) return 0;
6080     connectionSetAuthenticationFlags(hci_connection, AUTH_FLAG_READ_RSSI);
6081     hci_run();
6082     return 1;
6083 }
6084 
6085 /**
6086  * @brief Get connection type
6087  * @param con_handle
6088  * @result connection_type
6089  */
6090 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
6091     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6092     if (!conn) return GAP_CONNECTION_INVALID;
6093     switch (conn->address_type){
6094         case BD_ADDR_TYPE_LE_PUBLIC:
6095         case BD_ADDR_TYPE_LE_RANDOM:
6096             return GAP_CONNECTION_LE;
6097         case BD_ADDR_TYPE_SCO:
6098             return GAP_CONNECTION_SCO;
6099         case BD_ADDR_TYPE_ACL:
6100             return GAP_CONNECTION_ACL;
6101         default:
6102             return GAP_CONNECTION_INVALID;
6103     }
6104 }
6105 
6106 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
6107     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6108     if (!conn) return HCI_ROLE_INVALID;
6109     return (hci_role_t) conn->role;
6110 }
6111 
6112 
6113 #ifdef ENABLE_CLASSIC
6114 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
6115     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6116     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6117     conn->request_role = role;
6118     hci_run();
6119     return ERROR_CODE_SUCCESS;
6120 }
6121 #endif
6122 
6123 #ifdef ENABLE_BLE
6124 
6125 uint8_t gap_le_set_phy(hci_con_handle_t con_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){
6126     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6127     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6128 
6129     conn->le_phy_update_all_phys    = all_phys;
6130     conn->le_phy_update_tx_phys     = tx_phys;
6131     conn->le_phy_update_rx_phys     = rx_phys;
6132     conn->le_phy_update_phy_options = phy_options;
6133 
6134     hci_run();
6135 
6136     return 0;
6137 }
6138 
6139 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6140     // check if already in list
6141     btstack_linked_list_iterator_t it;
6142     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6143     while (btstack_linked_list_iterator_has_next(&it)) {
6144         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
6145         if (entry->address_type != address_type) {
6146             continue;
6147         }
6148         if (memcmp(entry->address, address, 6) != 0) {
6149             continue;
6150         }
6151 		// disallow if already scheduled to add
6152 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
6153 			return ERROR_CODE_COMMAND_DISALLOWED;
6154 		}
6155 		// still on controller, but scheduled to remove -> re-add
6156 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
6157 		return ERROR_CODE_SUCCESS;
6158     }
6159     // alloc and add to list
6160     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
6161     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
6162     entry->address_type = address_type;
6163     (void)memcpy(entry->address, address, 6);
6164     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
6165     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
6166     return ERROR_CODE_SUCCESS;
6167 }
6168 
6169 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6170     btstack_linked_list_iterator_t it;
6171     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6172     while (btstack_linked_list_iterator_has_next(&it)){
6173         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6174         if (entry->address_type != address_type) {
6175             continue;
6176         }
6177         if (memcmp(entry->address, address, 6) != 0) {
6178             continue;
6179         }
6180         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6181             // remove from controller if already present
6182             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6183         }  else {
6184             // directly remove entry from whitelist
6185             btstack_linked_list_iterator_remove(&it);
6186             btstack_memory_whitelist_entry_free(entry);
6187         }
6188         return ERROR_CODE_SUCCESS;
6189     }
6190     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6191 }
6192 
6193 static void hci_whitelist_clear(void){
6194     btstack_linked_list_iterator_t it;
6195     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6196     while (btstack_linked_list_iterator_has_next(&it)){
6197         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6198         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6199             // remove from controller if already present
6200             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6201             continue;
6202         }
6203         // directly remove entry from whitelist
6204         btstack_linked_list_iterator_remove(&it);
6205         btstack_memory_whitelist_entry_free(entry);
6206     }
6207 }
6208 
6209 /**
6210  * @brief Clear Whitelist
6211  * @returns 0 if ok
6212  */
6213 uint8_t gap_whitelist_clear(void){
6214     hci_whitelist_clear();
6215     hci_run();
6216     return ERROR_CODE_SUCCESS;
6217 }
6218 
6219 /**
6220  * @brief Add Device to Whitelist
6221  * @param address_typ
6222  * @param address
6223  * @returns 0 if ok
6224  */
6225 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6226     uint8_t status = hci_whitelist_add(address_type, address);
6227     if (status){
6228         return status;
6229     }
6230     hci_run();
6231     return ERROR_CODE_SUCCESS;
6232 }
6233 
6234 /**
6235  * @brief Remove Device from Whitelist
6236  * @param address_typ
6237  * @param address
6238  * @returns 0 if ok
6239  */
6240 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6241     uint8_t status = hci_whitelist_remove(address_type, address);
6242     if (status){
6243         return status;
6244     }
6245     hci_run();
6246     return ERROR_CODE_SUCCESS;
6247 }
6248 
6249 #ifdef ENABLE_LE_CENTRAL
6250 /**
6251  *  @brief Connect with Whitelist
6252  *  @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
6253  *  @returns - if ok
6254  */
6255 uint8_t gap_connect_with_whitelist(void){
6256     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6257         return ERROR_CODE_COMMAND_DISALLOWED;
6258     }
6259     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6260     hci_run();
6261     return ERROR_CODE_SUCCESS;
6262 }
6263 
6264 /**
6265  * @brief Auto Connection Establishment - Start Connecting to device
6266  * @param address_typ
6267  * @param address
6268  * @returns 0 if ok
6269  */
6270 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
6271     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6272         return ERROR_CODE_COMMAND_DISALLOWED;
6273     }
6274 
6275     uint8_t status = hci_whitelist_add(address_type, address);
6276     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
6277         return status;
6278     }
6279 
6280     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6281 
6282     hci_run();
6283     return ERROR_CODE_SUCCESS;
6284 }
6285 
6286 /**
6287  * @brief Auto Connection Establishment - Stop Connecting to device
6288  * @param address_typ
6289  * @param address
6290  * @returns 0 if ok
6291  */
6292 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
6293     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6294         return ERROR_CODE_COMMAND_DISALLOWED;
6295     }
6296 
6297     hci_whitelist_remove(address_type, address);
6298     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
6299         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6300     }
6301     hci_run();
6302     return 0;
6303 }
6304 
6305 /**
6306  * @brief Auto Connection Establishment - Stop everything
6307  * @note  Convenience function to stop all active auto connection attempts
6308  */
6309 uint8_t gap_auto_connection_stop_all(void){
6310     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
6311         return ERROR_CODE_COMMAND_DISALLOWED;
6312     }
6313     hci_whitelist_clear();
6314     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6315     hci_run();
6316     return ERROR_CODE_SUCCESS;
6317 }
6318 
6319 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
6320     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6321     if (!conn) return 0;
6322     return conn->le_connection_interval;
6323 }
6324 #endif
6325 #endif
6326 
6327 #ifdef ENABLE_CLASSIC
6328 /**
6329  * @brief Set Extended Inquiry Response data
6330  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
6331  * @note has to be done before stack starts up
6332  */
6333 void gap_set_extended_inquiry_response(const uint8_t * data){
6334     hci_stack->eir_data = data;
6335     hci_stack->gap_tasks |= GAP_TASK_SET_EIR_DATA;
6336     hci_run();
6337 }
6338 
6339 /**
6340  * @brief Start GAP Classic Inquiry
6341  * @param duration in 1.28s units
6342  * @return 0 if ok
6343  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
6344  */
6345 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
6346     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
6347     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6348     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
6349         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
6350     }
6351     hci_stack->inquiry_state = duration_in_1280ms_units;
6352     hci_run();
6353     return 0;
6354 }
6355 
6356 /**
6357  * @brief Stop GAP Classic Inquiry
6358  * @returns 0 if ok
6359  */
6360 int gap_inquiry_stop(void){
6361     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
6362         // emit inquiry complete event, before it even started
6363         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
6364         hci_emit_event(event, sizeof(event), 1);
6365         return 0;
6366     }
6367     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
6368     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
6369     hci_run();
6370     return 0;
6371 }
6372 
6373 void gap_inquiry_set_lap(uint32_t lap){
6374     hci_stack->inquiry_lap = lap;
6375 }
6376 
6377 
6378 /**
6379  * @brief Remote Name Request
6380  * @param addr
6381  * @param page_scan_repetition_mode
6382  * @param clock_offset only used when bit 15 is set
6383  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
6384  */
6385 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
6386     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6387     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
6388     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
6389     hci_stack->remote_name_clock_offset = clock_offset;
6390     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
6391     hci_run();
6392     return 0;
6393 }
6394 
6395 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
6396     hci_stack->gap_pairing_state = state;
6397     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
6398     hci_run();
6399     return 0;
6400 }
6401 
6402 /**
6403  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
6404  * @param addr
6405  * @param pin_data
6406  * @param pin_len
6407  * @return 0 if ok
6408  */
6409 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
6410     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6411     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
6412     hci_stack->gap_pairing_pin_len = pin_len;
6413     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
6414 }
6415 
6416 /**
6417  * @brief Legacy Pairing Pin Code Response
6418  * @param addr
6419  * @param pin
6420  * @return 0 if ok
6421  */
6422 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
6423     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
6424 }
6425 
6426 /**
6427  * @brief Abort Legacy Pairing
6428  * @param addr
6429  * @param pin
6430  * @return 0 if ok
6431  */
6432 int gap_pin_code_negative(bd_addr_t addr){
6433     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6434     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
6435 }
6436 
6437 /**
6438  * @brief SSP Passkey Response
6439  * @param addr
6440  * @param passkey
6441  * @return 0 if ok
6442  */
6443 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
6444     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6445     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
6446     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
6447 }
6448 
6449 /**
6450  * @brief Abort SSP Passkey Entry/Pairing
6451  * @param addr
6452  * @param pin
6453  * @return 0 if ok
6454  */
6455 int gap_ssp_passkey_negative(const bd_addr_t addr){
6456     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6457     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
6458 }
6459 
6460 /**
6461  * @brief Accept SSP Numeric Comparison
6462  * @param addr
6463  * @param passkey
6464  * @return 0 if ok
6465  */
6466 int gap_ssp_confirmation_response(const bd_addr_t addr){
6467     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6468     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
6469 }
6470 
6471 /**
6472  * @brief Abort SSP Numeric Comparison/Pairing
6473  * @param addr
6474  * @param pin
6475  * @return 0 if ok
6476  */
6477 int gap_ssp_confirmation_negative(const bd_addr_t addr){
6478     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6479     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
6480 }
6481 
6482 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
6483 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
6484     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6485     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6486     connectionSetAuthenticationFlags(conn, flag);
6487     hci_run();
6488     return ERROR_CODE_SUCCESS;
6489 }
6490 #endif
6491 
6492 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
6493 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
6494     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6495 }
6496 
6497 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
6498     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6499 }
6500 #endif
6501 
6502 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6503 /**
6504  * @brief Report Remote OOB Data
6505  * @param bd_addr
6506  * @param c_192 Simple Pairing Hash C derived from P-192 public key
6507  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
6508  * @param c_256 Simple Pairing Hash C derived from P-256 public key
6509  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
6510  */
6511 uint8_t gap_ssp_remote_oob_data(const bd_addr_t addr, const uint8_t * c_192, const uint8_t * r_192, const uint8_t * c_256, const uint8_t * r_256){
6512     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6513     if (connection == NULL) {
6514         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6515     }
6516     connection->classic_oob_c_192 = c_192;
6517     connection->classic_oob_r_192 = r_192;
6518 
6519     // ignore P-256 if not supported by us
6520     if (hci_stack->secure_connections_active){
6521         connection->classic_oob_c_256 = c_256;
6522         connection->classic_oob_r_256 = r_256;
6523     }
6524 
6525     return ERROR_CODE_SUCCESS;
6526 }
6527 /**
6528  * @brief Generate new OOB data
6529  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
6530  */
6531 void gap_ssp_generate_oob_data(void){
6532     hci_stack->classic_read_local_oob_data = true;
6533     hci_run();
6534 }
6535 
6536 #endif
6537 
6538 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
6539 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
6540     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6541     if (connection == NULL) {
6542         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6543     }
6544 
6545     memcpy(connection->link_key, link_key, sizeof(link_key_t));
6546     connection->link_key_type = type;
6547 
6548     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
6549 }
6550 
6551 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
6552 /**
6553  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
6554  * @param inquiry_mode see bluetooth_defines.h
6555  */
6556 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
6557     hci_stack->inquiry_mode = inquiry_mode;
6558 }
6559 
6560 /**
6561  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
6562  */
6563 void hci_set_sco_voice_setting(uint16_t voice_setting){
6564     hci_stack->sco_voice_setting = voice_setting;
6565 }
6566 
6567 /**
6568  * @brief Get SCO Voice Setting
6569  * @return current voice setting
6570  */
6571 uint16_t hci_get_sco_voice_setting(void){
6572     return hci_stack->sco_voice_setting;
6573 }
6574 
6575 static int hci_have_usb_transport(void){
6576     if (!hci_stack->hci_transport) return 0;
6577     const char * transport_name = hci_stack->hci_transport->name;
6578     if (!transport_name) return 0;
6579     return (transport_name[0] == 'H') && (transport_name[1] == '2');
6580 }
6581 
6582 /** @brief Get SCO packet length for current SCO Voice setting
6583  *  @note  Using SCO packets of the exact length is required for USB transfer
6584  *  @return Length of SCO packets in bytes (not audio frames)
6585  */
6586 uint16_t hci_get_sco_packet_length(void){
6587     uint16_t sco_packet_length = 0;
6588 
6589 #ifdef ENABLE_SCO_OVER_HCI
6590     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6591     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6592 
6593     if (hci_have_usb_transport()){
6594         // see Core Spec for H2 USB Transfer.
6595         // 3 byte SCO header + 24 bytes per connection
6596         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
6597         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
6598     } else {
6599         // 3 byte SCO header + SCO packet size over the air (60 bytes)
6600         sco_packet_length = 3 + 60 * multiplier;
6601         // assert that it still fits inside an SCO buffer
6602         if (sco_packet_length > hci_stack->sco_data_packet_length){
6603             sco_packet_length = 3 + 60;
6604         }
6605     }
6606 #endif
6607 
6608 #ifdef HAVE_SCO_TRANSPORT
6609     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6610     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6611     sco_packet_length = 3 + 60 * multiplier;
6612 #endif
6613     return sco_packet_length;
6614 }
6615 
6616 /**
6617 * @brief Sets the master/slave policy
6618 * @param policy (0: attempt to become master, 1: let connecting device decide)
6619 */
6620 void hci_set_master_slave_policy(uint8_t policy){
6621     hci_stack->master_slave_policy = policy;
6622 }
6623 
6624 #endif
6625 
6626 HCI_STATE hci_get_state(void){
6627     return hci_stack->state;
6628 }
6629 
6630 #ifdef ENABLE_CLASSIC
6631 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
6632     hci_stack->gap_classic_accept_callback = accept_callback;
6633 }
6634 #endif
6635 
6636 /**
6637  * @brief Set callback for Bluetooth Hardware Error
6638  */
6639 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
6640     hci_stack->hardware_error_callback = fn;
6641 }
6642 
6643 void hci_disconnect_all(void){
6644     btstack_linked_list_iterator_t it;
6645     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6646     while (btstack_linked_list_iterator_has_next(&it)){
6647         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6648         if (con->state == SENT_DISCONNECT) continue;
6649         con->state = SEND_DISCONNECT;
6650     }
6651     hci_run();
6652 }
6653 
6654 uint16_t hci_get_manufacturer(void){
6655     return hci_stack->manufacturer;
6656 }
6657 
6658 #ifdef ENABLE_BLE
6659 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
6660     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
6661     if (!hci_con) return NULL;
6662     return &hci_con->sm_connection;
6663 }
6664 
6665 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
6666 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
6667 #endif
6668 
6669 int gap_encryption_key_size(hci_con_handle_t con_handle){
6670     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6671     if (hci_connection == NULL) return 0;
6672     if (hci_is_le_connection(hci_connection)){
6673 #ifdef ENABLE_BLE
6674         sm_connection_t * sm_conn = &hci_connection->sm_connection;
6675         if (sm_conn->sm_connection_encrypted) {
6676             return sm_conn->sm_actual_encryption_key_size;
6677         }
6678 #endif
6679     } else {
6680 #ifdef ENABLE_CLASSIC
6681         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
6682             return hci_connection->encryption_key_size;
6683         }
6684 #endif
6685     }
6686     return 0;
6687 }
6688 
6689 int gap_authenticated(hci_con_handle_t con_handle){
6690     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6691     if (hci_connection == NULL) return 0;
6692 
6693     switch (hci_connection->address_type){
6694 #ifdef ENABLE_BLE
6695         case BD_ADDR_TYPE_LE_PUBLIC:
6696         case BD_ADDR_TYPE_LE_RANDOM:
6697             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6698             return hci_connection->sm_connection.sm_connection_authenticated;
6699 #endif
6700 #ifdef ENABLE_CLASSIC
6701         case BD_ADDR_TYPE_SCO:
6702         case BD_ADDR_TYPE_ACL:
6703             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
6704 #endif
6705         default:
6706             return 0;
6707     }
6708 }
6709 
6710 int gap_secure_connection(hci_con_handle_t con_handle){
6711     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6712     if (hci_connection == NULL) return 0;
6713 
6714     switch (hci_connection->address_type){
6715 #ifdef ENABLE_BLE
6716         case BD_ADDR_TYPE_LE_PUBLIC:
6717         case BD_ADDR_TYPE_LE_RANDOM:
6718             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6719             return hci_connection->sm_connection.sm_connection_sc;
6720 #endif
6721 #ifdef ENABLE_CLASSIC
6722         case BD_ADDR_TYPE_SCO:
6723         case BD_ADDR_TYPE_ACL:
6724             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
6725 #endif
6726         default:
6727             return 0;
6728     }
6729 }
6730 
6731 bool gap_bonded(hci_con_handle_t con_handle){
6732 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6733 	if (hci_connection == NULL) return 0;
6734 
6735 #ifdef ENABLE_CLASSIC
6736 	link_key_t link_key;
6737 	link_key_type_t link_key_type;
6738 #endif
6739 	switch (hci_connection->address_type){
6740 #ifdef ENABLE_BLE
6741 		case BD_ADDR_TYPE_LE_PUBLIC:
6742 		case BD_ADDR_TYPE_LE_RANDOM:
6743 			return hci_connection->sm_connection.sm_le_db_index >= 0;
6744 #endif
6745 #ifdef ENABLE_CLASSIC
6746 		case BD_ADDR_TYPE_SCO:
6747 		case BD_ADDR_TYPE_ACL:
6748 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
6749 #endif
6750 		default:
6751 			return false;
6752 	}
6753 }
6754 
6755 #ifdef ENABLE_BLE
6756 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
6757     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
6758     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
6759     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
6760     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
6761     return sm_conn->sm_connection_authorization_state;
6762 }
6763 #endif
6764 
6765 #ifdef ENABLE_CLASSIC
6766 uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){
6767     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6768     if (!conn) return GAP_CONNECTION_INVALID;
6769     conn->sniff_min_interval = sniff_min_interval;
6770     conn->sniff_max_interval = sniff_max_interval;
6771     conn->sniff_attempt = sniff_attempt;
6772     conn->sniff_timeout = sniff_timeout;
6773     hci_run();
6774     return 0;
6775 }
6776 
6777 /**
6778  * @brief Exit Sniff mode
6779  * @param con_handle
6780  @ @return 0 if ok
6781  */
6782 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
6783     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6784     if (!conn) return GAP_CONNECTION_INVALID;
6785     conn->sniff_min_interval = 0xffff;
6786     hci_run();
6787     return 0;
6788 }
6789 
6790 uint8_t gap_sniff_subrating_configure(hci_con_handle_t con_handle, uint16_t max_latency, uint16_t min_remote_timeout, uint16_t min_local_timeout){
6791     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6792     if (!conn) return GAP_CONNECTION_INVALID;
6793     conn->sniff_subrating_max_latency = max_latency;
6794     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
6795     conn->sniff_subrating_min_local_timeout = min_local_timeout;
6796     hci_run();
6797     return ERROR_CODE_SUCCESS;
6798 }
6799 
6800 uint8_t gap_qos_set(hci_con_handle_t con_handle, hci_service_type_t service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency, uint32_t delay_variation){
6801     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6802     if (!conn) return GAP_CONNECTION_INVALID;
6803     conn->qos_service_type = service_type;
6804     conn->qos_token_rate = token_rate;
6805     conn->qos_peak_bandwidth = peak_bandwidth;
6806     conn->qos_latency = latency;
6807     conn->qos_delay_variation = delay_variation;
6808     hci_run();
6809     return ERROR_CODE_SUCCESS;
6810 }
6811 
6812 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
6813     hci_stack->new_page_scan_interval = page_scan_interval;
6814     hci_stack->new_page_scan_window = page_scan_window;
6815     hci_stack->gap_tasks |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
6816     hci_run();
6817 }
6818 
6819 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
6820     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
6821     hci_stack->gap_tasks |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
6822     hci_run();
6823 }
6824 
6825 #endif
6826 
6827 void hci_halting_defer(void){
6828     if (hci_stack->state != HCI_STATE_HALTING) return;
6829     switch (hci_stack->substate){
6830         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
6831         case HCI_HALTING_CLOSE:
6832             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
6833             break;
6834         default:
6835             break;
6836     }
6837 }
6838 
6839 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6840 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
6841     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6842     if (le_device_db_index >= le_device_db_max_count()) return;
6843     uint8_t offset = le_device_db_index >> 3;
6844     uint8_t mask = 1 << (le_device_db_index & 7);
6845     hci_stack->le_resolving_list_add_entries[offset] |= mask;
6846     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6847     	// note: go back to remove entries, otherwise, a remove + add will skip the add
6848         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6849     }
6850 }
6851 
6852 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
6853 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6854 	if (le_device_db_index >= le_device_db_max_count()) return;
6855 	uint8_t offset = le_device_db_index >> 3;
6856 	uint8_t mask = 1 << (le_device_db_index & 7);
6857 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
6858 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6859 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6860 	}
6861 }
6862 
6863 uint8_t gap_load_resolving_list_from_le_device_db(void){
6864 	if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) {
6865 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
6866 	}
6867 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
6868 		// restart le resolving list update
6869 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6870 	}
6871 	return ERROR_CODE_SUCCESS;
6872 }
6873 #endif
6874 
6875 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
6876 void hci_setup_test_connections_fuzz(void){
6877     hci_connection_t * conn;
6878 
6879     // default address: 66:55:44:33:00:01
6880     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
6881 
6882     // setup Controller info
6883     hci_stack->num_cmd_packets = 255;
6884     hci_stack->acl_packets_total_num = 255;
6885 
6886     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
6887     addr[5] = 0x01;
6888     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6889     conn->con_handle = addr[5];
6890     conn->role  = HCI_ROLE_SLAVE;
6891     conn->state = RECEIVED_CONNECTION_REQUEST;
6892     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6893 
6894     // setup incoming Classic SCO connection with con handle 0x0002
6895     addr[5] = 0x02;
6896     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6897     conn->con_handle = addr[5];
6898     conn->role  = HCI_ROLE_SLAVE;
6899     conn->state = RECEIVED_CONNECTION_REQUEST;
6900     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6901 
6902     // setup ready Classic ACL connection with con handle 0x0003
6903     addr[5] = 0x03;
6904     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6905     conn->con_handle = addr[5];
6906     conn->role  = HCI_ROLE_SLAVE;
6907     conn->state = OPEN;
6908     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6909 
6910     // setup ready Classic SCO connection with con handle 0x0004
6911     addr[5] = 0x04;
6912     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6913     conn->con_handle = addr[5];
6914     conn->role  = HCI_ROLE_SLAVE;
6915     conn->state = OPEN;
6916     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6917 
6918     // setup ready LE ACL connection with con handle 0x005 and public address
6919     addr[5] = 0x05;
6920     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
6921     conn->con_handle = addr[5];
6922     conn->role  = HCI_ROLE_SLAVE;
6923     conn->state = OPEN;
6924     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6925     conn->sm_connection.sm_connection_encrypted = 1;
6926 }
6927 
6928 void hci_free_connections_fuzz(void){
6929     btstack_linked_list_iterator_t it;
6930     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6931     while (btstack_linked_list_iterator_has_next(&it)){
6932         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6933         btstack_linked_list_iterator_remove(&it);
6934         btstack_memory_hci_connection_free(con);
6935     }
6936 }
6937 void hci_simulate_working_fuzz(void){
6938     hci_init_done();
6939     hci_stack->num_cmd_packets = 255;
6940 }
6941 #endif
6942