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