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