xref: /btstack/src/hci.c (revision 03fbe9c6217fbce708f7e489cad973b2c1b19b12)
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 /*
39  *  hci.c
40  *
41  *  Created by Matthias Ringwald on 4/29/09.
42  *
43  */
44 
45 #include "btstack-config.h"
46 
47 #include "hci.h"
48 #include "gap.h"
49 
50 #include <stdarg.h>
51 #include <string.h>
52 #include <stdio.h>
53 
54 #ifndef EMBEDDED
55 #ifdef _WIN32
56 #include "Winsock2.h"
57 #else
58 #include <unistd.h> // gethostbyname
59 #endif
60 #include <btstack/version.h>
61 #endif
62 
63 #include "btstack_memory.h"
64 #include "debug.h"
65 #include "hci_dump.h"
66 
67 #include <btstack/linked_list.h>
68 #include <btstack/hci_cmds.h>
69 
70 #define HCI_CONNECTION_TIMEOUT_MS 10000
71 
72 #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
73 
74 #ifdef USE_BLUETOOL
75 #include "../platforms/ios/src/bt_control_iphone.h"
76 #endif
77 
78 static void hci_update_scan_enable(void);
79 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
80 static void hci_connection_timeout_handler(timer_source_t *timer);
81 static void hci_connection_timestamp(hci_connection_t *connection);
82 static int  hci_power_control_on(void);
83 static void hci_power_control_off(void);
84 static void hci_state_reset();
85 
86 // the STACK is here
87 #ifndef HAVE_MALLOC
88 static hci_stack_t   hci_stack_static;
89 #endif
90 static hci_stack_t * hci_stack = NULL;
91 
92 // test helper
93 static uint8_t disable_l2cap_timeouts = 0;
94 
95 /**
96  * create connection for given address
97  *
98  * @return connection OR NULL, if no memory left
99  */
100 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
101     log_info("create_connection_for_addr %s", bd_addr_to_str(addr));
102     hci_connection_t * conn = btstack_memory_hci_connection_get();
103     if (!conn) return NULL;
104     memset(conn, 0, sizeof(hci_connection_t));
105     BD_ADDR_COPY(conn->address, addr);
106     conn->address_type = addr_type;
107     conn->con_handle = 0xffff;
108     conn->authentication_flags = AUTH_FLAGS_NONE;
109     conn->bonding_flags = 0;
110     conn->requested_security_level = LEVEL_0;
111     linked_item_set_user(&conn->timeout.item, conn);
112     conn->timeout.process = hci_connection_timeout_handler;
113     hci_connection_timestamp(conn);
114     conn->acl_recombination_length = 0;
115     conn->acl_recombination_pos = 0;
116     conn->num_acl_packets_sent = 0;
117     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
118     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
119     return conn;
120 }
121 
122 
123 /**
124  * get le connection parameter range
125 *
126  * @return le connection parameter range struct
127  */
128 le_connection_parameter_range_t gap_le_get_connection_parameter_range(){
129     return hci_stack->le_connection_parameter_range;
130 }
131 
132 /**
133  * set le connection parameter range
134  *
135  */
136 
137 void gap_le_set_connection_parameter_range(le_connection_parameter_range_t range){
138     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_interval_min;
139     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_interval_max;
140     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_latency_min;
141     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_latency_max;
142     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = range.le_supervision_timeout_min;
143     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = range.le_supervision_timeout_max;
144 }
145 
146 /**
147  * get hci connections iterator
148  *
149  * @return hci connections iterator
150  */
151 
152 void hci_connections_get_iterator(linked_list_iterator_t *it){
153     linked_list_iterator_init(it, &hci_stack->connections);
154 }
155 
156 /**
157  * get connection for a given handle
158  *
159  * @return connection OR NULL, if not found
160  */
161 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
162     linked_list_iterator_t it;
163     linked_list_iterator_init(&it, &hci_stack->connections);
164     while (linked_list_iterator_has_next(&it)){
165         hci_connection_t * item = (hci_connection_t *) linked_list_iterator_next(&it);
166         if ( item->con_handle == con_handle ) {
167             return item;
168         }
169     }
170     return NULL;
171 }
172 
173 /**
174  * get connection for given address
175  *
176  * @return connection OR NULL, if not found
177  */
178 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
179     linked_list_iterator_t it;
180     linked_list_iterator_init(&it, &hci_stack->connections);
181     while (linked_list_iterator_has_next(&it)){
182         hci_connection_t * connection = (hci_connection_t *) linked_list_iterator_next(&it);
183         if (connection->address_type != addr_type)  continue;
184         if (memcmp(addr, connection->address, 6) != 0) continue;
185         return connection;
186     }
187     return NULL;
188 }
189 
190 static void hci_connection_timeout_handler(timer_source_t *timer){
191     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
192 #ifdef HAVE_TIME
193     struct timeval tv;
194     gettimeofday(&tv, NULL);
195     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
196         // connections might be timed out
197         hci_emit_l2cap_check_timeout(connection);
198     }
199 #endif
200 #ifdef HAVE_TICK
201     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
202         // connections might be timed out
203         hci_emit_l2cap_check_timeout(connection);
204     }
205 #endif
206     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
207     run_loop_add_timer(timer);
208 }
209 
210 static void hci_connection_timestamp(hci_connection_t *connection){
211 #ifdef HAVE_TIME
212     gettimeofday(&connection->timestamp, NULL);
213 #endif
214 #ifdef HAVE_TICK
215     connection->timestamp = embedded_get_ticks();
216 #endif
217 }
218 
219 
220 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
221     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
222 }
223 
224 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
225     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
226 }
227 
228 
229 /**
230  * add authentication flags and reset timer
231  * @note: assumes classic connection
232  */
233 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
234     bd_addr_t addr;
235     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
236     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
237     if (conn) {
238         connectionSetAuthenticationFlags(conn, flags);
239         hci_connection_timestamp(conn);
240     }
241 }
242 
243 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
244     hci_connection_t * conn = hci_connection_for_handle(handle);
245     if (!conn) return 0;
246     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
247     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
248     return 0;
249 }
250 
251 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
252     if (hci_stack->remote_device_db) {
253         hci_stack->remote_device_db->delete_link_key(addr);
254     }
255 }
256 
257 int hci_is_le_connection(hci_connection_t * connection){
258     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
259     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
260 }
261 
262 
263 /**
264  * count connections
265  */
266 static int nr_hci_connections(void){
267     int count = 0;
268     linked_item_t *it;
269     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
270     return count;
271 }
272 
273 /**
274  * Dummy handler called by HCI
275  */
276 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
277 }
278 
279 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
280     hci_connection_t * connection = hci_connection_for_handle(handle);
281     if (!connection) {
282         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
283         return 0;
284     }
285     return connection->num_acl_packets_sent;
286 }
287 
288 uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
289 
290     int num_packets_sent_classic = 0;
291     int num_packets_sent_le = 0;
292 
293     bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN;
294 
295     linked_item_t *it;
296     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
297         hci_connection_t * connection = (hci_connection_t *) it;
298         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
299             num_packets_sent_classic += connection->num_acl_packets_sent;
300         } else {
301             num_packets_sent_le += connection->num_acl_packets_sent;
302         }
303         // ignore connections that are not open, e.g., in state RECEIVED_DISCONNECTION_COMPLETE
304         if (connection->con_handle == con_handle && connection->state == OPEN){
305             address_type = connection->address_type;
306         }
307     }
308 
309     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
310     int free_slots_le = 0;
311 
312     if (free_slots_classic < 0){
313         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);
314         return 0;
315     }
316 
317     if (hci_stack->le_acl_packets_total_num){
318         // if we have LE slots, they are used
319         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
320         if (free_slots_le < 0){
321             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);
322             return 0;
323         }
324     } else {
325         // otherwise, classic slots are used for LE, too
326         free_slots_classic -= num_packets_sent_le;
327         if (free_slots_classic < 0){
328             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);
329             return 0;
330         }
331     }
332 
333     switch (address_type){
334         case BD_ADDR_TYPE_UNKNOWN:
335             log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
336             return 0;
337 
338         case BD_ADDR_TYPE_CLASSIC:
339             return free_slots_classic;
340 
341         default:
342            if (hci_stack->le_acl_packets_total_num){
343                return free_slots_le;
344            }
345            return free_slots_classic;
346     }
347 }
348 
349 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
350 int hci_can_send_command_packet_now(void){
351     if (hci_stack->hci_packet_buffer_reserved) return 0;
352 
353     // check for async hci transport implementations
354     if (hci_stack->hci_transport->can_send_packet_now){
355         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
356             return 0;
357         }
358     }
359 
360     return hci_stack->num_cmd_packets > 0;
361 }
362 
363 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
364     // check for async hci transport implementations
365     if (hci_stack->hci_transport->can_send_packet_now){
366         if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){
367             return 0;
368         }
369     }
370     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
371 }
372 
373 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
374     if (hci_stack->hci_packet_buffer_reserved) return 0;
375     return hci_can_send_prepared_acl_packet_now(con_handle);
376 }
377 
378 // used for internal checks in l2cap[-le].c
379 int hci_is_packet_buffer_reserved(void){
380     return hci_stack->hci_packet_buffer_reserved;
381 }
382 
383 // reserves outgoing packet buffer. @returns 1 if successful
384 int hci_reserve_packet_buffer(void){
385     if (hci_stack->hci_packet_buffer_reserved) {
386         log_error("hci_reserve_packet_buffer called but buffer already reserved");
387         return 0;
388     }
389     hci_stack->hci_packet_buffer_reserved = 1;
390     return 1;
391 }
392 
393 void hci_release_packet_buffer(void){
394     hci_stack->hci_packet_buffer_reserved = 0;
395 }
396 
397 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
398 int hci_transport_synchronous(void){
399     return hci_stack->hci_transport->can_send_packet_now == NULL;
400 }
401 
402 uint16_t hci_max_acl_le_data_packet_length(void){
403     return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length;
404 }
405 
406 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
407 
408     // 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);
409 
410     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
411     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
412     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
413         max_acl_data_packet_length = hci_stack->le_data_packets_length;
414     }
415 
416     // testing: reduce buffer to minimum
417     // max_acl_data_packet_length = 52;
418 
419     int err;
420     // multiple packets could be send on a synchronous HCI transport
421     while (1){
422 
423         // get current data
424         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
425         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
426         int more_fragments = 0;
427 
428         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
429         if (current_acl_data_packet_length > max_acl_data_packet_length){
430             more_fragments = 1;
431             current_acl_data_packet_length = max_acl_data_packet_length;
432         }
433 
434         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
435         if (acl_header_pos > 0){
436             uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0);
437             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
438             bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
439         }
440 
441         // update header len
442         bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
443 
444         // count packet
445         connection->num_acl_packets_sent++;
446 
447         // send packet
448         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
449         const int size = current_acl_data_packet_length + 4;
450         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
451         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
452 
453         // done yet?
454         if (!more_fragments) break;
455 
456         // update start of next fragment to send
457         hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
458 
459         // can send more?
460         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
461     }
462 
463     // done
464     hci_stack->acl_fragmentation_pos = 0;
465     hci_stack->acl_fragmentation_total_size = 0;
466 
467     // release buffer now for synchronous transport
468     if (hci_transport_synchronous()){
469         hci_release_packet_buffer();
470     }
471 
472     return err;
473 }
474 
475 // pre: caller has reserved the packet buffer
476 int hci_send_acl_packet_buffer(int size){
477 
478     // log_info("hci_send_acl_packet_buffer size %u", size);
479 
480     if (!hci_stack->hci_packet_buffer_reserved) {
481         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
482         return 0;
483     }
484 
485     uint8_t * packet = hci_stack->hci_packet_buffer;
486     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
487 
488     // check for free places on Bluetooth module
489     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
490         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
491         hci_release_packet_buffer();
492         return BTSTACK_ACL_BUFFERS_FULL;
493     }
494 
495     hci_connection_t *connection = hci_connection_for_handle( con_handle);
496     if (!connection) {
497         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
498         hci_release_packet_buffer();
499         return 0;
500     }
501     hci_connection_timestamp(connection);
502 
503     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
504 
505     // setup data
506     hci_stack->acl_fragmentation_total_size = size;
507     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
508 
509     return hci_send_acl_packet_fragments(connection);
510 }
511 
512 static void acl_handler(uint8_t *packet, int size){
513 
514     // log_info("acl_handler: size %u", size);
515 
516     // get info
517     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
518     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
519     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
520     uint16_t acl_length         = READ_ACL_LENGTH(packet);
521 
522     // ignore non-registered handle
523     if (!conn){
524         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
525         return;
526     }
527 
528     // assert packet is complete
529     if (acl_length + 4 != size){
530         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
531         return;
532     }
533 
534     // update idle timestamp
535     hci_connection_timestamp(conn);
536 
537     // handle different packet types
538     switch (acl_flags & 0x03) {
539 
540         case 0x01: // continuation fragment
541 
542             // sanity checks
543             if (conn->acl_recombination_pos == 0) {
544                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
545                 return;
546             }
547             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
548                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
549                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
550                 conn->acl_recombination_pos = 0;
551                 return;
552             }
553 
554             // append fragment payload (header already stored)
555             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
556             conn->acl_recombination_pos += acl_length;
557 
558             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
559             //        conn->acl_recombination_pos, conn->acl_recombination_length);
560 
561             // forward complete L2CAP packet if complete.
562             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
563 
564                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, &conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
565                 // reset recombination buffer
566                 conn->acl_recombination_length = 0;
567                 conn->acl_recombination_pos = 0;
568             }
569             break;
570 
571         case 0x02: { // first fragment
572 
573             // sanity check
574             if (conn->acl_recombination_pos) {
575                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
576                 conn->acl_recombination_pos = 0;
577             }
578 
579             // peek into L2CAP packet!
580             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
581 
582             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
583 
584             // compare fragment size to L2CAP packet size
585             if (acl_length >= l2cap_length + 4){
586 
587                 // forward fragment as L2CAP packet
588                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
589 
590             } else {
591 
592                 if (acl_length > HCI_ACL_BUFFER_SIZE){
593                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
594                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
595                     return;
596                 }
597 
598                 // store first fragment and tweak acl length for complete package
599                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
600                 conn->acl_recombination_pos    = acl_length + 4;
601                 conn->acl_recombination_length = l2cap_length;
602                 bt_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
603             }
604             break;
605 
606         }
607         default:
608             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
609             return;
610     }
611 
612     // execute main loop
613     hci_run();
614 }
615 
616 static void hci_shutdown_connection(hci_connection_t *conn){
617     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
618 
619     run_loop_remove_timer(&conn->timeout);
620 
621     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
622     btstack_memory_hci_connection_free( conn );
623 
624     // now it's gone
625     hci_emit_nr_connections_changed();
626 }
627 
628 static const uint16_t packet_type_sizes[] = {
629     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
630     HCI_ACL_DH1_SIZE, 0, 0, 0,
631     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
632     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
633 };
634 static const uint8_t  packet_type_feature_requirement_bit[] = {
635      0, // 3 slot packets
636      1, // 5 slot packets
637     25, // EDR 2 mpbs
638     26, // EDR 3 mbps
639     39, // 3 slot EDR packts
640     40, // 5 slot EDR packet
641 };
642 static const uint16_t packet_type_feature_packet_mask[] = {
643     0x0f00, // 3 slot packets
644     0xf000, // 5 slot packets
645     0x1102, // EDR 2 mpbs
646     0x2204, // EDR 3 mbps
647     0x0300, // 3 slot EDR packts
648     0x3000, // 5 slot EDR packet
649 };
650 
651 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
652     // enable packet types based on size
653     uint16_t packet_types = 0;
654     unsigned int i;
655     for (i=0;i<16;i++){
656         if (packet_type_sizes[i] == 0) continue;
657         if (packet_type_sizes[i] <= buffer_size){
658             packet_types |= 1 << i;
659         }
660     }
661     // disable packet types due to missing local supported features
662     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
663         int bit_idx = packet_type_feature_requirement_bit[i];
664         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
665         if (feature_set) continue;
666         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
667         packet_types &= ~packet_type_feature_packet_mask[i];
668     }
669     // flip bits for "may not be used"
670     packet_types ^= 0x3306;
671     return packet_types;
672 }
673 
674 uint16_t hci_usable_acl_packet_types(void){
675     return hci_stack->packet_types;
676 }
677 
678 uint8_t* hci_get_outgoing_packet_buffer(void){
679     // hci packet buffer is >= acl data packet length
680     return hci_stack->hci_packet_buffer;
681 }
682 
683 uint16_t hci_max_acl_data_packet_length(void){
684     return hci_stack->acl_data_packet_length;
685 }
686 
687 int hci_non_flushable_packet_boundary_flag_supported(void){
688     // No. 54, byte 6, bit 6
689     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
690 }
691 
692 int hci_ssp_supported(void){
693     // No. 51, byte 6, bit 3
694     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
695 }
696 
697 int hci_classic_supported(void){
698     // No. 37, byte 4, bit 5, = No BR/EDR Support
699     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
700 }
701 
702 int hci_le_supported(void){
703 #ifdef HAVE_BLE
704     // No. 37, byte 4, bit 6 = LE Supported (Controller)
705     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
706 #else
707     return 0;
708 #endif
709 }
710 
711 // get addr type and address used in advertisement packets
712 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
713     *addr_type = hci_stack->adv_addr_type;
714     if (hci_stack->adv_addr_type){
715         memcpy(addr, hci_stack->adv_address, 6);
716     } else {
717         memcpy(addr, hci_stack->local_bd_addr, 6);
718     }
719 }
720 
721 #ifdef HAVE_BLE
722 void le_handle_advertisement_report(uint8_t *packet, int size){
723     int offset = 3;
724     int num_reports = packet[offset];
725     offset += 1;
726 
727     int i;
728     log_info("HCI: handle adv report with num reports: %d", num_reports);
729     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
730     for (i=0; i<num_reports;i++){
731         uint8_t data_length = packet[offset + 8];
732         int pos = 0;
733         event[pos++] = GAP_LE_ADVERTISING_REPORT;
734         event[pos++] = event_size;
735         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
736         offset += 8;
737         pos += 8;
738         event[pos++] = packet[offset + 1 + data_length]; // rssi
739         event[pos++] = packet[offset++]; //data_length;
740         memcpy(&event[pos], &packet[offset], data_length);
741         pos += data_length;
742         offset += data_length + 1; // rssi
743         hci_dump_packet( HCI_EVENT_PACKET, 0, event, pos);
744         hci_stack->packet_handler(HCI_EVENT_PACKET, event, pos);
745     }
746 }
747 #endif
748 
749 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
750     uint8_t command_completed = 0;
751     if ((hci_stack->substate % 2) == 0) return;
752     // odd: waiting for event
753     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
754         uint16_t opcode = READ_BT_16(packet,3);
755         if (opcode == hci_stack->last_cmd_opcode){
756             command_completed = 1;
757             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate >> 1);
758         } else {
759             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
760         }
761     }
762     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
763         uint8_t  status = packet[2];
764         uint16_t opcode = READ_BT_16(packet,4);
765         if (opcode == hci_stack->last_cmd_opcode){
766             if (status){
767                 command_completed = 1;
768                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate >> 1);
769             } else {
770                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
771             }
772         } else {
773             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
774         }
775     }
776 
777     if (!command_completed) return;
778 
779     switch(hci_stack->substate >> 1){
780         default:
781             hci_stack->substate++;
782             break;
783     }
784 }
785 
786 static void hci_initializing_state_machine(){
787     if (hci_stack->substate % 2) {
788         // odd: waiting for command completion
789         return;
790     }
791     // log_info("hci_init: substate %u", hci_stack->substate >> 1);
792     switch (hci_stack->substate >> 1){
793         case 0: // RESET
794             hci_state_reset();
795 
796             hci_send_cmd(&hci_reset);
797             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
798                 // skip baud change
799                 hci_stack->substate = 2 << 1;
800             }
801             break;
802         case 1: // SEND BAUD CHANGE
803             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
804             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
805             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
806             break;
807         case 2: // LOCAL BAUD CHANGE
808             log_info("Local baud rate change");
809             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
810             hci_stack->substate += 2;
811             // break missing here for fall through
812 
813         case 3: // SET BD ADDR
814             if ( hci_stack->custom_bd_addr_set && hci_stack->control && hci_stack->control->set_bd_addr_cmd){
815                 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
816                 hci_stack->control->set_bd_addr_cmd(hci_stack->config, hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
817                 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
818                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
819                 break;
820             }
821             hci_stack->substate += 2;
822             // break missing here for fall through
823 
824         case 4:
825             log_info("Custom init");
826             // Custom initialization
827             if (hci_stack->control && hci_stack->control->next_cmd){
828                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
829                 if (valid_cmd){
830                     int size = 3 + hci_stack->hci_packet_buffer[2];
831                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
832                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
833                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
834                     hci_stack->substate = 3 << 1; // more init commands
835                     break;
836                 }
837                 log_info("hci_run: init script done");
838             }
839             // otherwise continue
840             hci_send_cmd(&hci_read_bd_addr);
841             break;
842         case 5:
843             hci_send_cmd(&hci_read_buffer_size);
844             break;
845         case 6:
846             hci_send_cmd(&hci_read_local_supported_features);
847             break;
848         case 7:
849             if (hci_le_supported()){
850                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
851             } else {
852                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
853                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
854             }
855 
856             // skip Classic init commands for LE only chipsets
857             if (!hci_classic_supported()){
858                 if (hci_le_supported()){
859                     hci_stack->substate = 12 << 1;    // skip all classic command
860                 } else {
861                     log_error("Neither BR/EDR nor LE supported");
862                     hci_stack->substate = 15 << 1;    // skip all
863                 }
864             }
865             break;
866         case 8:
867             if (hci_ssp_supported()){
868                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
869                 break;
870             }
871             hci_stack->substate += 2;
872             // break missing here for fall through
873 
874         case 9:
875             // ca. 15 sec
876             hci_send_cmd(&hci_write_page_timeout, 0x6000);
877             break;
878         case 10:
879             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
880             break;
881         case 11:
882             if (hci_stack->local_name){
883                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
884             } else {
885                 char hostname[30];
886 #ifdef EMBEDDED
887                 // BTstack-11:22:33:44:55:66
888                 strcpy(hostname, "BTstack ");
889                 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
890                 log_info("---> Name %s", hostname);
891 #else
892                 // hostname for POSIX systems
893                 gethostname(hostname, 30);
894                 hostname[29] = '\0';
895 #endif
896                 hci_send_cmd(&hci_write_local_name, hostname);
897             }
898             break;
899         case 12:
900             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
901             if (!hci_le_supported()){
902                 // SKIP LE init for Classic only configuration
903                 hci_stack->substate = 15 << 1;
904             }
905             break;
906 
907 #ifdef HAVE_BLE
908         // LE INIT
909         case 13:
910             hci_send_cmd(&hci_le_read_buffer_size);
911             break;
912         case 14:
913             // LE Supported Host = 1, Simultaneous Host = 0
914             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
915             break;
916         case 15:
917             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
918             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
919             break;
920 #endif
921 
922         // DONE
923         case 16:
924             // done.
925             hci_stack->state = HCI_STATE_WORKING;
926             hci_emit_state();
927             break;
928         default:
929             break;
930     }
931     hci_stack->substate++;
932 }
933 
934 // avoid huge local variables
935 #ifndef EMBEDDED
936 static device_name_t device_name;
937 #endif
938 static void event_handler(uint8_t *packet, int size){
939 
940     uint16_t event_length = packet[1];
941 
942     // assert packet is complete
943     if (size != event_length + 2){
944         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
945         return;
946     }
947 
948     bd_addr_t addr;
949     bd_addr_type_t addr_type;
950     uint8_t link_type;
951     hci_con_handle_t handle;
952     hci_connection_t * conn;
953     int i;
954 
955     // log_info("HCI:EVENT:%02x", packet[0]);
956 
957     switch (packet[0]) {
958 
959         case HCI_EVENT_COMMAND_COMPLETE:
960             // get num cmd packets
961             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
962             hci_stack->num_cmd_packets = packet[2];
963 
964             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
965                 // from offset 5
966                 // status
967                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
968                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
969                 // ignore: SCO data packet len (8)
970                 hci_stack->acl_packets_total_num  = packet[9];
971                 // ignore: total num SCO packets
972                 if (hci_stack->state == HCI_STATE_INITIALIZING){
973                     // determine usable ACL payload size
974                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
975                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
976                     }
977                     log_info("hci_read_buffer_size: used size %u, count %u",
978                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num);
979                 }
980             }
981 #ifdef HAVE_BLE
982             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
983                 hci_stack->le_data_packets_length = READ_BT_16(packet, 6);
984                 hci_stack->le_acl_packets_total_num  = packet[8];
985                     // determine usable ACL payload size
986                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
987                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
988                     }
989                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
990             }
991 #endif
992             // Dump local address
993             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
994                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
995                 log_info("Local Address, Status: 0x%02x: Addr: %s",
996                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
997             }
998             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
999                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1000             }
1001             // Note: HCI init checks
1002             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
1003                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1004                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
1005                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
1006                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
1007                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
1008                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
1009 
1010                 // determine usable ACL packet types based on host buffer size and supported features
1011                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1012                 log_info("packet types %04x", hci_stack->packet_types);
1013 
1014                 // Classic/LE
1015                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1016             }
1017             break;
1018 
1019         case HCI_EVENT_COMMAND_STATUS:
1020             // get num cmd packets
1021             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
1022             hci_stack->num_cmd_packets = packet[3];
1023             break;
1024 
1025         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1026             int offset = 3;
1027             for (i=0; i<packet[2];i++){
1028                 handle = READ_BT_16(packet, offset);
1029                 offset += 2;
1030                 uint16_t num_packets = READ_BT_16(packet, offset);
1031                 offset += 2;
1032 
1033                 conn = hci_connection_for_handle(handle);
1034                 if (!conn){
1035                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1036                     continue;
1037                 }
1038 
1039                 if (conn->num_acl_packets_sent >= num_packets){
1040                     conn->num_acl_packets_sent -= num_packets;
1041                 } else {
1042                     log_error("hci_number_completed_packets, more slots freed then sent.");
1043                     conn->num_acl_packets_sent = 0;
1044                 }
1045                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1046             }
1047             break;
1048         }
1049         case HCI_EVENT_CONNECTION_REQUEST:
1050             bt_flip_addr(addr, &packet[2]);
1051             // TODO: eval COD 8-10
1052             link_type = packet[11];
1053             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1054             if (link_type == 1) { // ACL
1055                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1056                 if (!conn) {
1057                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1058                 }
1059                 if (!conn) {
1060                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1061                     hci_stack->decline_reason = 0x0d;
1062                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
1063                     break;
1064                 }
1065                 conn->state = RECEIVED_CONNECTION_REQUEST;
1066                 hci_run();
1067             } else {
1068                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
1069                 hci_stack->decline_reason = 0x0a;
1070                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
1071             }
1072             break;
1073 
1074         case HCI_EVENT_CONNECTION_COMPLETE:
1075             // Connection management
1076             bt_flip_addr(addr, &packet[5]);
1077             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1078             addr_type = BD_ADDR_TYPE_CLASSIC;
1079             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1080             if (conn) {
1081                 if (!packet[2]){
1082                     conn->state = OPEN;
1083                     conn->con_handle = READ_BT_16(packet, 3);
1084                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1085 
1086                     // restart timer
1087                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1088                     run_loop_add_timer(&conn->timeout);
1089 
1090                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1091 
1092                     hci_emit_nr_connections_changed();
1093                 } else {
1094                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1095                     uint8_t status = packet[2];
1096                     bd_addr_t bd_address;
1097                     memcpy(&bd_address, conn->address, 6);
1098 
1099                     // connection failed, remove entry
1100                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1101                     btstack_memory_hci_connection_free( conn );
1102 
1103                     // notify client if dedicated bonding
1104                     if (notify_dedicated_bonding_failed){
1105                         log_info("hci notify_dedicated_bonding_failed");
1106                         hci_emit_dedicated_bonding_result(bd_address, status);
1107                     }
1108 
1109                     // if authentication error, also delete link key
1110                     if (packet[2] == 0x05) {
1111                         hci_drop_link_key_for_bd_addr(&addr);
1112                     }
1113                 }
1114             }
1115             break;
1116 
1117         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1118             handle = READ_BT_16(packet, 3);
1119             conn = hci_connection_for_handle(handle);
1120             if (!conn) break;
1121             if (!packet[2]){
1122                 uint8_t * features = &packet[5];
1123                 if (features[6] & (1 << 3)){
1124                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1125                 }
1126             }
1127             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1128             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1129             if (conn->bonding_flags & BONDING_DEDICATED){
1130                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1131             }
1132             break;
1133 
1134         case HCI_EVENT_LINK_KEY_REQUEST:
1135             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1136             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1137             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1138             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
1139             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1140             hci_run();
1141             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1142             return;
1143 
1144         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1145             bt_flip_addr(addr, &packet[2]);
1146             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1147             if (!conn) break;
1148             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1149             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1150             // Change Connection Encryption keeps link key type
1151             if (link_key_type != CHANGED_COMBINATION_KEY){
1152                 conn->link_key_type = link_key_type;
1153             }
1154             if (!hci_stack->remote_device_db) break;
1155             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
1156             // still forward event to allow dismiss of pairing dialog
1157             break;
1158         }
1159 
1160         case HCI_EVENT_PIN_CODE_REQUEST:
1161             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1162             // non-bondable mode: pin code negative reply will be sent
1163             if (!hci_stack->bondable){
1164                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1165                 hci_run();
1166                 return;
1167             }
1168             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1169             if (!hci_stack->remote_device_db) break;
1170             bt_flip_addr(addr, &packet[2]);
1171             hci_stack->remote_device_db->delete_link_key(&addr);
1172             break;
1173 
1174         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1175             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1176             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1177             break;
1178 
1179         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1180             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1181             if (!hci_stack->ssp_auto_accept) break;
1182             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1183             break;
1184 
1185         case HCI_EVENT_USER_PASSKEY_REQUEST:
1186             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1187             if (!hci_stack->ssp_auto_accept) break;
1188             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1189             break;
1190 
1191         case HCI_EVENT_ENCRYPTION_CHANGE:
1192             handle = READ_BT_16(packet, 3);
1193             conn = hci_connection_for_handle(handle);
1194             if (!conn) break;
1195             if (packet[2] == 0) {
1196                 if (packet[5]){
1197                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1198                 } else {
1199                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1200                 }
1201             }
1202             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1203             break;
1204 
1205         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1206             handle = READ_BT_16(packet, 3);
1207             conn = hci_connection_for_handle(handle);
1208             if (!conn) break;
1209 
1210             // dedicated bonding: send result and disconnect
1211             if (conn->bonding_flags & BONDING_DEDICATED){
1212                 conn->bonding_flags &= ~BONDING_DEDICATED;
1213                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1214                 conn->bonding_status = packet[2];
1215                 break;
1216             }
1217 
1218             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1219                 // link key sufficient for requested security
1220                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1221                 break;
1222             }
1223             // not enough
1224             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1225             break;
1226 
1227 #ifndef EMBEDDED
1228         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1229             if (!hci_stack->remote_device_db) break;
1230             if (packet[2]) break; // status not ok
1231             bt_flip_addr(addr, &packet[3]);
1232             // fix for invalid remote names - terminate on 0xff
1233             for (i=0; i<248;i++){
1234                 if (packet[9+i] == 0xff){
1235                     packet[9+i] = 0;
1236                     break;
1237                 }
1238             }
1239             memset(&device_name, 0, sizeof(device_name_t));
1240             strncpy((char*) device_name, (char*) &packet[9], 248);
1241             hci_stack->remote_device_db->put_name(&addr, &device_name);
1242             break;
1243 
1244         case HCI_EVENT_INQUIRY_RESULT:
1245         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
1246             if (!hci_stack->remote_device_db) break;
1247             // first send inq result packet
1248             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1249             // then send cached remote names
1250             int offset = 3;
1251             for (i=0; i<packet[2];i++){
1252                 bt_flip_addr(addr, &packet[offset]);
1253                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
1254                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
1255                     hci_emit_remote_name_cached(&addr, &device_name);
1256                 }
1257             }
1258             return;
1259         }
1260 #endif
1261 
1262         // HCI_EVENT_DISCONNECTION_COMPLETE
1263         // has been split, to first notify stack before shutting connection down
1264         // see end of function, too.
1265         case HCI_EVENT_DISCONNECTION_COMPLETE:
1266             if (packet[2]) break;   // status != 0
1267             handle = READ_BT_16(packet, 3);
1268             hci_connection_t * conn = hci_connection_for_handle(handle);
1269             if (!conn) break;       // no conn struct anymore
1270             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1271             break;
1272 
1273         case HCI_EVENT_HARDWARE_ERROR:
1274             if(hci_stack->control && hci_stack->control->hw_error){
1275                 (*hci_stack->control->hw_error)();
1276             } else {
1277                 // if no special requests, just reboot stack
1278                 hci_power_control_off();
1279                 hci_power_control_on();
1280             }
1281             break;
1282 
1283         case DAEMON_EVENT_HCI_PACKET_SENT:
1284             // release packet buffer only for asynchronous transport and if there are not further fragements
1285             if (hci_transport_synchronous()) {
1286                 log_error("Synchronous HCI Transport shouldn't send DAEMON_EVENT_HCI_PACKET_SENT");
1287                 return; // instead of break: to avoid re-entering hci_run()
1288             }
1289             if (hci_stack->acl_fragmentation_total_size) break;
1290             hci_release_packet_buffer();
1291             break;
1292 
1293 #ifdef HAVE_BLE
1294         case HCI_EVENT_LE_META:
1295             switch (packet[2]){
1296                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1297                     log_info("advertising report received");
1298                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1299                     le_handle_advertisement_report(packet, size);
1300                     break;
1301                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1302                     // Connection management
1303                     bt_flip_addr(addr, &packet[8]);
1304                     addr_type = (bd_addr_type_t)packet[7];
1305                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1306                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1307                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1308                     if (packet[3]){
1309                         if (conn){
1310                             // outgoing connection failed, remove entry
1311                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1312                             btstack_memory_hci_connection_free( conn );
1313                         }
1314                         // if authentication error, also delete link key
1315                         if (packet[3] == 0x05) {
1316                             hci_drop_link_key_for_bd_addr(&addr);
1317                         }
1318                         break;
1319                     }
1320                     if (!conn){
1321                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1322                     }
1323                     if (!conn){
1324                         // no memory
1325                         break;
1326                     }
1327 
1328                     conn->state = OPEN;
1329                     conn->con_handle = READ_BT_16(packet, 4);
1330 
1331                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1332 
1333                     // restart timer
1334                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1335                     // run_loop_add_timer(&conn->timeout);
1336 
1337                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1338 
1339                     hci_emit_nr_connections_changed();
1340                     break;
1341 
1342             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
1343 
1344                 default:
1345                     break;
1346             }
1347             break;
1348 #endif
1349         default:
1350             break;
1351     }
1352 
1353     // handle BT initialization
1354     if (hci_stack->state == HCI_STATE_INITIALIZING){
1355         hci_initializing_event_handler(packet, size);
1356     }
1357 
1358     // help with BT sleep
1359     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1360         && hci_stack->substate == 1
1361         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1362         hci_stack->substate++;
1363     }
1364 
1365     // notify upper stack
1366     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1367 
1368     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1369     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1370         if (!packet[2]){
1371             handle = READ_BT_16(packet, 3);
1372             hci_connection_t * conn = hci_connection_for_handle(handle);
1373             if (conn) {
1374                 uint8_t status = conn->bonding_status;
1375                 uint16_t flags = conn->bonding_flags;
1376                 bd_addr_t bd_address;
1377                 memcpy(&bd_address, conn->address, 6);
1378                 hci_shutdown_connection(conn);
1379                 // connection struct is gone, don't access anymore
1380                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1381                     hci_emit_dedicated_bonding_result(bd_address, status);
1382                 }
1383             }
1384         }
1385     }
1386 
1387 	// execute main loop
1388 	hci_run();
1389 }
1390 
1391 static void sco_handler(uint8_t * packet, uint16_t size){
1392     // not handled yet
1393 }
1394 
1395 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1396     hci_dump_packet(packet_type, 1, packet, size);
1397     switch (packet_type) {
1398         case HCI_EVENT_PACKET:
1399             event_handler(packet, size);
1400             break;
1401         case HCI_ACL_DATA_PACKET:
1402             acl_handler(packet, size);
1403             break;
1404         case HCI_SCO_DATA_PACKET:
1405             sco_handler(packet, size);
1406         default:
1407             break;
1408     }
1409 }
1410 
1411 /** Register HCI packet handlers */
1412 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1413     hci_stack->packet_handler = handler;
1414 }
1415 
1416 static void hci_state_reset(){
1417     // no connections yet
1418     hci_stack->connections = NULL;
1419 
1420     // keep discoverable/connectable as this has been requested by the client(s)
1421     // hci_stack->discoverable = 0;
1422     // hci_stack->connectable = 0;
1423     // hci_stack->bondable = 1;
1424 
1425     // buffer is free
1426     hci_stack->hci_packet_buffer_reserved = 0;
1427 
1428     // no pending cmds
1429     hci_stack->decline_reason = 0;
1430     hci_stack->new_scan_enable_value = 0xff;
1431 
1432     // LE
1433     hci_stack->adv_addr_type = 0;
1434     memset(hci_stack->adv_address, 0, 6);
1435     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1436     hci_stack->le_scan_type = 0xff;
1437     hci_stack->le_connection_parameter_range.le_conn_interval_min = 0x0006;
1438     hci_stack->le_connection_parameter_range.le_conn_interval_max = 0x0C80;
1439     hci_stack->le_connection_parameter_range.le_conn_latency_min = 0x0000;
1440     hci_stack->le_connection_parameter_range.le_conn_latency_max = 0x03E8;
1441     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 0x000A;
1442     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 0x0C80;
1443 }
1444 
1445 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1446 
1447 #ifdef HAVE_MALLOC
1448     if (!hci_stack) {
1449         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1450     }
1451 #else
1452     hci_stack = &hci_stack_static;
1453 #endif
1454     memset(hci_stack, 0, sizeof(hci_stack_t));
1455 
1456     // reference to use transport layer implementation
1457     hci_stack->hci_transport = transport;
1458 
1459     // references to used control implementation
1460     hci_stack->control = control;
1461 
1462     // reference to used config
1463     hci_stack->config = config;
1464 
1465     // higher level handler
1466     hci_stack->packet_handler = dummy_handler;
1467 
1468     // store and open remote device db
1469     hci_stack->remote_device_db = remote_device_db;
1470     if (hci_stack->remote_device_db) {
1471         hci_stack->remote_device_db->open();
1472     }
1473 
1474     // max acl payload size defined in config.h
1475     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1476 
1477     // register packet handlers with transport
1478     transport->register_packet_handler(&packet_handler);
1479 
1480     hci_stack->state = HCI_STATE_OFF;
1481 
1482     // class of device
1483     hci_stack->class_of_device = 0x007a020c; // Smartphone
1484 
1485     // bondable by default
1486     hci_stack->bondable = 1;
1487 
1488     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1489     hci_stack->ssp_enable = 1;
1490     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1491     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1492     hci_stack->ssp_auto_accept = 1;
1493 
1494     hci_state_reset();
1495 }
1496 
1497 void hci_close(){
1498     // close remote device db
1499     if (hci_stack->remote_device_db) {
1500         hci_stack->remote_device_db->close();
1501     }
1502     while (hci_stack->connections) {
1503         // cancel all l2cap connections
1504         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1505         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1506     }
1507     hci_power_control(HCI_POWER_OFF);
1508 
1509 #ifdef HAVE_MALLOC
1510     free(hci_stack);
1511 #endif
1512     hci_stack = NULL;
1513 }
1514 
1515 void hci_set_class_of_device(uint32_t class_of_device){
1516     hci_stack->class_of_device = class_of_device;
1517 }
1518 
1519 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
1520 void hci_set_bd_addr(bd_addr_t addr){
1521     memcpy(hci_stack->custom_bd_addr, addr, 6);
1522     hci_stack->custom_bd_addr_set = 1;
1523 }
1524 
1525 void hci_disable_l2cap_timeout_check(){
1526     disable_l2cap_timeouts = 1;
1527 }
1528 // State-Module-Driver overview
1529 // state                    module  low-level
1530 // HCI_STATE_OFF             off      close
1531 // HCI_STATE_INITIALIZING,   on       open
1532 // HCI_STATE_WORKING,        on       open
1533 // HCI_STATE_HALTING,        on       open
1534 // HCI_STATE_SLEEPING,    off/sleep   close
1535 // HCI_STATE_FALLING_ASLEEP  on       open
1536 
1537 static int hci_power_control_on(void){
1538 
1539     // power on
1540     int err = 0;
1541     if (hci_stack->control && hci_stack->control->on){
1542         err = (*hci_stack->control->on)(hci_stack->config);
1543     }
1544     if (err){
1545         log_error( "POWER_ON failed");
1546         hci_emit_hci_open_failed();
1547         return err;
1548     }
1549 
1550     // open low-level device
1551     err = hci_stack->hci_transport->open(hci_stack->config);
1552     if (err){
1553         log_error( "HCI_INIT failed, turning Bluetooth off again");
1554         if (hci_stack->control && hci_stack->control->off){
1555             (*hci_stack->control->off)(hci_stack->config);
1556         }
1557         hci_emit_hci_open_failed();
1558         return err;
1559     }
1560     return 0;
1561 }
1562 
1563 static void hci_power_control_off(void){
1564 
1565     log_info("hci_power_control_off");
1566 
1567     // close low-level device
1568     hci_stack->hci_transport->close(hci_stack->config);
1569 
1570     log_info("hci_power_control_off - hci_transport closed");
1571 
1572     // power off
1573     if (hci_stack->control && hci_stack->control->off){
1574         (*hci_stack->control->off)(hci_stack->config);
1575     }
1576 
1577     log_info("hci_power_control_off - control closed");
1578 
1579     hci_stack->state = HCI_STATE_OFF;
1580 }
1581 
1582 static void hci_power_control_sleep(void){
1583 
1584     log_info("hci_power_control_sleep");
1585 
1586 #if 0
1587     // don't close serial port during sleep
1588 
1589     // close low-level device
1590     hci_stack->hci_transport->close(hci_stack->config);
1591 #endif
1592 
1593     // sleep mode
1594     if (hci_stack->control && hci_stack->control->sleep){
1595         (*hci_stack->control->sleep)(hci_stack->config);
1596     }
1597 
1598     hci_stack->state = HCI_STATE_SLEEPING;
1599 }
1600 
1601 static int hci_power_control_wake(void){
1602 
1603     log_info("hci_power_control_wake");
1604 
1605     // wake on
1606     if (hci_stack->control && hci_stack->control->wake){
1607         (*hci_stack->control->wake)(hci_stack->config);
1608     }
1609 
1610 #if 0
1611     // open low-level device
1612     int err = hci_stack->hci_transport->open(hci_stack->config);
1613     if (err){
1614         log_error( "HCI_INIT failed, turning Bluetooth off again");
1615         if (hci_stack->control && hci_stack->control->off){
1616             (*hci_stack->control->off)(hci_stack->config);
1617         }
1618         hci_emit_hci_open_failed();
1619         return err;
1620     }
1621 #endif
1622 
1623     return 0;
1624 }
1625 
1626 static void hci_power_transition_to_initializing(void){
1627     // set up state machine
1628     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1629     hci_stack->hci_packet_buffer_reserved = 0;
1630     hci_stack->state = HCI_STATE_INITIALIZING;
1631     hci_stack->substate = 0;
1632 }
1633 
1634 int hci_power_control(HCI_POWER_MODE power_mode){
1635 
1636     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1637 
1638     int err = 0;
1639     switch (hci_stack->state){
1640 
1641         case HCI_STATE_OFF:
1642             switch (power_mode){
1643                 case HCI_POWER_ON:
1644                     err = hci_power_control_on();
1645                     if (err) {
1646                         log_error("hci_power_control_on() error %u", err);
1647                         return err;
1648                     }
1649                     hci_power_transition_to_initializing();
1650                     break;
1651                 case HCI_POWER_OFF:
1652                     // do nothing
1653                     break;
1654                 case HCI_POWER_SLEEP:
1655                     // do nothing (with SLEEP == OFF)
1656                     break;
1657             }
1658             break;
1659 
1660         case HCI_STATE_INITIALIZING:
1661             switch (power_mode){
1662                 case HCI_POWER_ON:
1663                     // do nothing
1664                     break;
1665                 case HCI_POWER_OFF:
1666                     // no connections yet, just turn it off
1667                     hci_power_control_off();
1668                     break;
1669                 case HCI_POWER_SLEEP:
1670                     // no connections yet, just turn it off
1671                     hci_power_control_sleep();
1672                     break;
1673             }
1674             break;
1675 
1676         case HCI_STATE_WORKING:
1677             switch (power_mode){
1678                 case HCI_POWER_ON:
1679                     // do nothing
1680                     break;
1681                 case HCI_POWER_OFF:
1682                     // see hci_run
1683                     hci_stack->state = HCI_STATE_HALTING;
1684                     break;
1685                 case HCI_POWER_SLEEP:
1686                     // see hci_run
1687                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1688                     hci_stack->substate = 0;
1689                     break;
1690             }
1691             break;
1692 
1693         case HCI_STATE_HALTING:
1694             switch (power_mode){
1695                 case HCI_POWER_ON:
1696                     hci_power_transition_to_initializing();
1697                     break;
1698                 case HCI_POWER_OFF:
1699                     // do nothing
1700                     break;
1701                 case HCI_POWER_SLEEP:
1702                     // see hci_run
1703                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1704                     hci_stack->substate = 0;
1705                     break;
1706             }
1707             break;
1708 
1709         case HCI_STATE_FALLING_ASLEEP:
1710             switch (power_mode){
1711                 case HCI_POWER_ON:
1712 
1713 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1714                     // nothing to do, if H4 supports power management
1715                     if (bt_control_iphone_power_management_enabled()){
1716                         hci_stack->state = HCI_STATE_INITIALIZING;
1717                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1718                         break;
1719                     }
1720 #endif
1721                     hci_power_transition_to_initializing();
1722                     break;
1723                 case HCI_POWER_OFF:
1724                     // see hci_run
1725                     hci_stack->state = HCI_STATE_HALTING;
1726                     break;
1727                 case HCI_POWER_SLEEP:
1728                     // do nothing
1729                     break;
1730             }
1731             break;
1732 
1733         case HCI_STATE_SLEEPING:
1734             switch (power_mode){
1735                 case HCI_POWER_ON:
1736 
1737 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1738                     // nothing to do, if H4 supports power management
1739                     if (bt_control_iphone_power_management_enabled()){
1740                         hci_stack->state = HCI_STATE_INITIALIZING;
1741                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1742                         hci_update_scan_enable();
1743                         break;
1744                     }
1745 #endif
1746                     err = hci_power_control_wake();
1747                     if (err) return err;
1748                     hci_power_transition_to_initializing();
1749                     break;
1750                 case HCI_POWER_OFF:
1751                     hci_stack->state = HCI_STATE_HALTING;
1752                     break;
1753                 case HCI_POWER_SLEEP:
1754                     // do nothing
1755                     break;
1756             }
1757             break;
1758     }
1759 
1760     // create internal event
1761 	hci_emit_state();
1762 
1763 	// trigger next/first action
1764 	hci_run();
1765 
1766     return 0;
1767 }
1768 
1769 static void hci_update_scan_enable(void){
1770     // 2 = page scan, 1 = inq scan
1771     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1772     hci_run();
1773 }
1774 
1775 void hci_discoverable_control(uint8_t enable){
1776     if (enable) enable = 1; // normalize argument
1777 
1778     if (hci_stack->discoverable == enable){
1779         hci_emit_discoverable_enabled(hci_stack->discoverable);
1780         return;
1781     }
1782 
1783     hci_stack->discoverable = enable;
1784     hci_update_scan_enable();
1785 }
1786 
1787 void hci_connectable_control(uint8_t enable){
1788     if (enable) enable = 1; // normalize argument
1789 
1790     // don't emit event
1791     if (hci_stack->connectable == enable) return;
1792 
1793     hci_stack->connectable = enable;
1794     hci_update_scan_enable();
1795 }
1796 
1797 bd_addr_t * hci_local_bd_addr(void){
1798     return &hci_stack->local_bd_addr;
1799 }
1800 
1801 void hci_run(){
1802 
1803     hci_connection_t * connection;
1804     linked_item_t * it;
1805 
1806     // send continuation fragments first, as they block the prepared packet buffer
1807     if (hci_stack->acl_fragmentation_total_size > 0) {
1808         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1809         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1810             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1811             if (connection) {
1812                 hci_send_acl_packet_fragments(connection);
1813                 return;
1814             }
1815             // connection gone -> discard further fragments
1816             hci_stack->acl_fragmentation_total_size = 0;
1817             hci_stack->acl_fragmentation_pos = 0;
1818         }
1819     }
1820 
1821     if (!hci_can_send_command_packet_now()) return;
1822 
1823     // global/non-connection oriented commands
1824 
1825     // decline incoming connections
1826     if (hci_stack->decline_reason){
1827         uint8_t reason = hci_stack->decline_reason;
1828         hci_stack->decline_reason = 0;
1829         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1830         return;
1831     }
1832 
1833     // send scan enable
1834     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1835         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1836         hci_stack->new_scan_enable_value = 0xff;
1837         return;
1838     }
1839 
1840 #ifdef HAVE_BLE
1841     // handle le scan
1842     if (hci_stack->state == HCI_STATE_WORKING){
1843         switch(hci_stack->le_scanning_state){
1844             case LE_START_SCAN:
1845                 hci_stack->le_scanning_state = LE_SCANNING;
1846                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1847                 return;
1848 
1849             case LE_STOP_SCAN:
1850                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1851                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1852                 return;
1853             default:
1854                 break;
1855         }
1856         if (hci_stack->le_scan_type != 0xff){
1857             // defaults: active scanning, accept all advertisement packets
1858             int scan_type = hci_stack->le_scan_type;
1859             hci_stack->le_scan_type = 0xff;
1860             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0);
1861             return;
1862         }
1863     }
1864 #endif
1865 
1866     // send pending HCI commands
1867     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1868         connection = (hci_connection_t *) it;
1869 
1870         switch(connection->state){
1871             case SEND_CREATE_CONNECTION:
1872                 switch(connection->address_type){
1873                     case BD_ADDR_TYPE_CLASSIC:
1874                         log_info("sending hci_create_connection");
1875                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1876                         break;
1877                     default:
1878 #ifdef HAVE_BLE
1879                         log_info("sending hci_le_create_connection");
1880                         hci_send_cmd(&hci_le_create_connection,
1881                                      0x0060,    // scan interval: 60 ms
1882                                      0x0030,    // scan interval: 30 ms
1883                                      0,         // don't use whitelist
1884                                      connection->address_type, // peer address type
1885                                      connection->address,      // peer bd addr
1886                                      hci_stack->adv_addr_type, // our addr type:
1887                                      0x0008,    // conn interval min
1888                                      0x0018,    // conn interval max
1889                                      0,         // conn latency
1890                                      0x0048,    // supervision timeout
1891                                      0x0001,    // min ce length
1892                                      0x0001     // max ce length
1893                                      );
1894 
1895                         connection->state = SENT_CREATE_CONNECTION;
1896 #endif
1897                         break;
1898                 }
1899                 return;
1900 
1901             case RECEIVED_CONNECTION_REQUEST:
1902                 log_info("sending hci_accept_connection_request");
1903                 connection->state = ACCEPTED_CONNECTION_REQUEST;
1904                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1905                 return;
1906 
1907 #ifdef HAVE_BLE
1908             case SEND_CANCEL_CONNECTION:
1909                 connection->state = SENT_CANCEL_CONNECTION;
1910                 hci_send_cmd(&hci_le_create_connection_cancel);
1911                 return;
1912 #endif
1913             case SEND_DISCONNECT:
1914                 connection->state = SENT_DISCONNECT;
1915                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1916                 return;
1917 
1918             default:
1919                 break;
1920         }
1921 
1922         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1923             log_info("responding to link key request");
1924             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1925             link_key_t link_key;
1926             link_key_type_t link_key_type;
1927             if ( hci_stack->remote_device_db
1928               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1929               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1930                connection->link_key_type = link_key_type;
1931                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1932             } else {
1933                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1934             }
1935             return;
1936         }
1937 
1938         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1939             log_info("denying to pin request");
1940             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1941             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1942             return;
1943         }
1944 
1945         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1946             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1947             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1948             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1949                 // tweak authentication requirements
1950                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1951                 if (connection->bonding_flags & BONDING_DEDICATED){
1952                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1953                 }
1954                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1955                     authreq |= 1;
1956                 }
1957                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1958             } else {
1959                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1960             }
1961             return;
1962         }
1963 
1964         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1965             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1966             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1967             return;
1968         }
1969 
1970         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1971             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1972             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1973             return;
1974         }
1975 
1976         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1977             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1978             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1979             return;
1980         }
1981 
1982         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1983             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1984             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1985             return;
1986         }
1987         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1988             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1989             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
1990             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1991             return;
1992         }
1993         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1994             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1995             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1996             return;
1997         }
1998         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1999             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2000             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2001             return;
2002         }
2003 
2004 #ifdef HAVE_BLE
2005         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2006             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2007 
2008             uint16_t connection_interval_min = connection->le_conn_interval_min;
2009             connection->le_conn_interval_min = 0;
2010             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2011                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2012                 0x0000, 0xffff);
2013         }
2014 #endif
2015     }
2016 
2017     switch (hci_stack->state){
2018         case HCI_STATE_INITIALIZING:
2019             hci_initializing_state_machine();
2020             break;
2021 
2022         case HCI_STATE_HALTING:
2023 
2024             log_info("HCI_STATE_HALTING");
2025             // close all open connections
2026             connection =  (hci_connection_t *) hci_stack->connections;
2027             if (connection){
2028 
2029                 // send disconnect
2030                 if (!hci_can_send_command_packet_now()) return;
2031 
2032                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2033                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2034 
2035                 // send disconnected event right away - causes higher layer connections to get closed, too.
2036                 hci_shutdown_connection(connection);
2037                 return;
2038             }
2039             log_info("HCI_STATE_HALTING, calling off");
2040 
2041             // switch mode
2042             hci_power_control_off();
2043 
2044             log_info("HCI_STATE_HALTING, emitting state");
2045             hci_emit_state();
2046             log_info("HCI_STATE_HALTING, done");
2047             break;
2048 
2049         case HCI_STATE_FALLING_ASLEEP:
2050             switch(hci_stack->substate) {
2051                 case 0:
2052                     log_info("HCI_STATE_FALLING_ASLEEP");
2053                     // close all open connections
2054                     connection =  (hci_connection_t *) hci_stack->connections;
2055 
2056 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2057                     // don't close connections, if H4 supports power management
2058                     if (bt_control_iphone_power_management_enabled()){
2059                         connection = NULL;
2060                     }
2061 #endif
2062                     if (connection){
2063 
2064                         // send disconnect
2065                         if (!hci_can_send_command_packet_now()) return;
2066 
2067                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2068                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2069 
2070                         // send disconnected event right away - causes higher layer connections to get closed, too.
2071                         hci_shutdown_connection(connection);
2072                         return;
2073                     }
2074 
2075                     if (hci_classic_supported()){
2076                         // disable page and inquiry scan
2077                         if (!hci_can_send_command_packet_now()) return;
2078 
2079                         log_info("HCI_STATE_HALTING, disabling inq scans");
2080                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
2081 
2082                         // continue in next sub state
2083                         hci_stack->substate++;
2084                         break;
2085                     }
2086                     // fall through for ble-only chips
2087 
2088                 case 2:
2089                     log_info("HCI_STATE_HALTING, calling sleep");
2090 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2091                     // don't actually go to sleep, if H4 supports power management
2092                     if (bt_control_iphone_power_management_enabled()){
2093                         // SLEEP MODE reached
2094                         hci_stack->state = HCI_STATE_SLEEPING;
2095                         hci_emit_state();
2096                         break;
2097                     }
2098 #endif
2099                     // switch mode
2100                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2101                     hci_emit_state();
2102                     break;
2103 
2104                 default:
2105                     break;
2106             }
2107             break;
2108 
2109         default:
2110             break;
2111     }
2112 }
2113 
2114 int hci_send_cmd_packet(uint8_t *packet, int size){
2115     bd_addr_t addr;
2116     hci_connection_t * conn;
2117     // house-keeping
2118 
2119     // create_connection?
2120     if (IS_COMMAND(packet, hci_create_connection)){
2121         bt_flip_addr(addr, &packet[3]);
2122         log_info("Create_connection to %s", bd_addr_to_str(addr));
2123 
2124         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2125         if (!conn){
2126             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2127             if (!conn){
2128                 // notify client that alloc failed
2129                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2130                 return 0; // don't sent packet to controller
2131             }
2132             conn->state = SEND_CREATE_CONNECTION;
2133         }
2134         log_info("conn state %u", conn->state);
2135         switch (conn->state){
2136             // if connection active exists
2137             case OPEN:
2138                 // and OPEN, emit connection complete command, don't send to controller
2139                 hci_emit_connection_complete(conn, 0);
2140                 return 0;
2141             case SEND_CREATE_CONNECTION:
2142                 // connection created by hci, e.g. dedicated bonding
2143                 break;
2144             default:
2145                 // otherwise, just ignore as it is already in the open process
2146                 return 0;
2147         }
2148         conn->state = SENT_CREATE_CONNECTION;
2149     }
2150 
2151     if (IS_COMMAND(packet, hci_link_key_request_reply)){
2152         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
2153     }
2154     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
2155         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
2156     }
2157 
2158     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2159         if (hci_stack->remote_device_db){
2160             bt_flip_addr(addr, &packet[3]);
2161             hci_stack->remote_device_db->delete_link_key(&addr);
2162         }
2163     }
2164 
2165     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2166     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2167         bt_flip_addr(addr, &packet[3]);
2168         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2169         if (conn){
2170             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2171         }
2172     }
2173 
2174     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2175     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2176     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2177     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2178         bt_flip_addr(addr, &packet[3]);
2179         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2180         if (conn){
2181             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2182         }
2183     }
2184 
2185 #ifdef HAVE_BLE
2186     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2187         hci_stack->adv_addr_type = packet[8];
2188     }
2189     if (IS_COMMAND(packet, hci_le_set_random_address)){
2190         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2191     }
2192 #endif
2193 
2194     hci_stack->num_cmd_packets--;
2195 
2196     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2197     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2198 
2199     // release packet buffer for synchronous transport implementations
2200     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2201         hci_stack->hci_packet_buffer_reserved = 0;
2202     }
2203 
2204     return err;
2205 }
2206 
2207 // disconnect because of security block
2208 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2209     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2210     if (!connection) return;
2211     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2212 }
2213 
2214 
2215 // Configure Secure Simple Pairing
2216 
2217 // enable will enable SSP during init
2218 void hci_ssp_set_enable(int enable){
2219     hci_stack->ssp_enable = enable;
2220 }
2221 
2222 int hci_local_ssp_activated(){
2223     return hci_ssp_supported() && hci_stack->ssp_enable;
2224 }
2225 
2226 // if set, BTstack will respond to io capability request using authentication requirement
2227 void hci_ssp_set_io_capability(int io_capability){
2228     hci_stack->ssp_io_capability = io_capability;
2229 }
2230 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2231     hci_stack->ssp_authentication_requirement = authentication_requirement;
2232 }
2233 
2234 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2235 void hci_ssp_set_auto_accept(int auto_accept){
2236     hci_stack->ssp_auto_accept = auto_accept;
2237 }
2238 
2239 /**
2240  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2241  */
2242 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2243 
2244     if (!hci_can_send_command_packet_now()){
2245         log_error("hci_send_cmd called but cannot send packet now");
2246         return 0;
2247     }
2248 
2249     // for HCI INITIALIZATION
2250     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2251     hci_stack->last_cmd_opcode = cmd->opcode;
2252 
2253     hci_reserve_packet_buffer();
2254     uint8_t * packet = hci_stack->hci_packet_buffer;
2255 
2256     va_list argptr;
2257     va_start(argptr, cmd);
2258     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
2259     va_end(argptr);
2260 
2261     return hci_send_cmd_packet(packet, size);
2262 }
2263 
2264 // Create various non-HCI events.
2265 // TODO: generalize, use table similar to hci_create_command
2266 
2267 void hci_emit_state(){
2268     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2269     uint8_t event[3];
2270     event[0] = BTSTACK_EVENT_STATE;
2271     event[1] = sizeof(event) - 2;
2272     event[2] = hci_stack->state;
2273     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2274     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2275 }
2276 
2277 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2278     uint8_t event[13];
2279     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2280     event[1] = sizeof(event) - 2;
2281     event[2] = status;
2282     bt_store_16(event, 3, conn->con_handle);
2283     bt_flip_addr(&event[5], conn->address);
2284     event[11] = 1; // ACL connection
2285     event[12] = 0; // encryption disabled
2286     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2287     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2288 }
2289 
2290 void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t * address, uint16_t conn_handle, uint8_t status){
2291     uint8_t event[21];
2292     event[0] = HCI_EVENT_LE_META;
2293     event[1] = sizeof(event) - 2;
2294     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2295     event[3] = status;
2296     bt_store_16(event, 4, conn_handle);
2297     event[6] = 0; // TODO: role
2298     event[7] = address_type;
2299     bt_flip_addr(&event[8], *address);
2300     bt_store_16(event, 14, 0); // interval
2301     bt_store_16(event, 16, 0); // latency
2302     bt_store_16(event, 18, 0); // supervision timeout
2303     event[20] = 0; // master clock accuracy
2304     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2305     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2306 }
2307 
2308 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2309     uint8_t event[6];
2310     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2311     event[1] = sizeof(event) - 2;
2312     event[2] = 0; // status = OK
2313     bt_store_16(event, 3, handle);
2314     event[5] = reason;
2315     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2316     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2317 }
2318 
2319 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2320     if (disable_l2cap_timeouts) return;
2321     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2322     uint8_t event[4];
2323     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2324     event[1] = sizeof(event) - 2;
2325     bt_store_16(event, 2, conn->con_handle);
2326     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2327     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2328 }
2329 
2330 void hci_emit_nr_connections_changed(){
2331     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2332     uint8_t event[3];
2333     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2334     event[1] = sizeof(event) - 2;
2335     event[2] = nr_hci_connections();
2336     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2337     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2338 }
2339 
2340 void hci_emit_hci_open_failed(){
2341     log_info("BTSTACK_EVENT_POWERON_FAILED");
2342     uint8_t event[2];
2343     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2344     event[1] = sizeof(event) - 2;
2345     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2346     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2347 }
2348 
2349 #ifndef EMBEDDED
2350 void hci_emit_btstack_version() {
2351     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2352     uint8_t event[6];
2353     event[0] = BTSTACK_EVENT_VERSION;
2354     event[1] = sizeof(event) - 2;
2355     event[2] = BTSTACK_MAJOR;
2356     event[3] = BTSTACK_MINOR;
2357     bt_store_16(event, 4, BTSTACK_REVISION);
2358     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2359     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2360 }
2361 #endif
2362 
2363 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2364     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2365     uint8_t event[3];
2366     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2367     event[1] = sizeof(event) - 2;
2368     event[2] = enabled;
2369     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2370     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2371 }
2372 
2373 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2374     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2375     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2376     event[1] = sizeof(event) - 2 - 1;
2377     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
2378     bt_flip_addr(&event[3], *addr);
2379     memcpy(&event[9], name, 248);
2380 
2381     event[9+248] = 0;   // assert \0 for log_info
2382     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2383 
2384     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2385     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2386 }
2387 
2388 void hci_emit_discoverable_enabled(uint8_t enabled){
2389     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2390     uint8_t event[3];
2391     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2392     event[1] = sizeof(event) - 2;
2393     event[2] = enabled;
2394     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2395     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2396 }
2397 
2398 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2399     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2400     uint8_t event[5];
2401     int pos = 0;
2402     event[pos++] = GAP_SECURITY_LEVEL;
2403     event[pos++] = sizeof(event) - 2;
2404     bt_store_16(event, 2, con_handle);
2405     pos += 2;
2406     event[pos++] = level;
2407     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2408     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2409 }
2410 
2411 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2412     log_info("hci_emit_dedicated_bonding_result %u ", status);
2413     uint8_t event[9];
2414     int pos = 0;
2415     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2416     event[pos++] = sizeof(event) - 2;
2417     event[pos++] = status;
2418     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2419     pos += 6;
2420     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2421     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2422 }
2423 
2424 // query if remote side supports SSP
2425 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2426     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2427     if (!connection) return 0;
2428     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2429 }
2430 
2431 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2432     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2433 }
2434 
2435 // GAP API
2436 /**
2437  * @bbrief enable/disable bonding. default is enabled
2438  * @praram enabled
2439  */
2440 void gap_set_bondable_mode(int enable){
2441     hci_stack->bondable = enable ? 1 : 0;
2442 }
2443 
2444 /**
2445  * @brief map link keys to security levels
2446  */
2447 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2448     switch (link_key_type){
2449         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2450             return LEVEL_4;
2451         case COMBINATION_KEY:
2452         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2453             return LEVEL_3;
2454         default:
2455             return LEVEL_2;
2456     }
2457 }
2458 
2459 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2460     if (!connection) return LEVEL_0;
2461     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2462     return gap_security_level_for_link_key_type(connection->link_key_type);
2463 }
2464 
2465 
2466 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2467     log_info("gap_mitm_protection_required_for_security_level %u", level);
2468     return level > LEVEL_2;
2469 }
2470 
2471 /**
2472  * @brief get current security level
2473  */
2474 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2475     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2476     if (!connection) return LEVEL_0;
2477     return gap_security_level_for_connection(connection);
2478 }
2479 
2480 /**
2481  * @brief request connection to device to
2482  * @result GAP_AUTHENTICATION_RESULT
2483  */
2484 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2485     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2486     if (!connection){
2487         hci_emit_security_level(con_handle, LEVEL_0);
2488         return;
2489     }
2490     gap_security_level_t current_level = gap_security_level(con_handle);
2491     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2492     if (current_level >= requested_level){
2493         hci_emit_security_level(con_handle, current_level);
2494         return;
2495     }
2496 
2497     connection->requested_security_level = requested_level;
2498 
2499 #if 0
2500     // sending encryption request without a link key results in an error.
2501     // TODO: figure out how to use it properly
2502 
2503     // would enabling ecnryption suffice (>= LEVEL_2)?
2504     if (hci_stack->remote_device_db){
2505         link_key_type_t link_key_type;
2506         link_key_t      link_key;
2507         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2508             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2509                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2510                 return;
2511             }
2512         }
2513     }
2514 #endif
2515 
2516     // try to authenticate connection
2517     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2518     hci_run();
2519 }
2520 
2521 /**
2522  * @brief start dedicated bonding with device. disconnect after bonding
2523  * @param device
2524  * @param request MITM protection
2525  * @result GAP_DEDICATED_BONDING_COMPLETE
2526  */
2527 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2528 
2529     // create connection state machine
2530     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2531 
2532     if (!connection){
2533         return BTSTACK_MEMORY_ALLOC_FAILED;
2534     }
2535 
2536     // delete linkn key
2537     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2538 
2539     // configure LEVEL_2/3, dedicated bonding
2540     connection->state = SEND_CREATE_CONNECTION;
2541     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2542     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2543     connection->bonding_flags = BONDING_DEDICATED;
2544 
2545     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2546 
2547     // handle: connnection failure (connection complete != ok)
2548     // handle: authentication failure
2549     // handle: disconnect on done
2550 
2551     hci_run();
2552 
2553     return 0;
2554 }
2555 
2556 void gap_set_local_name(const char * local_name){
2557     hci_stack->local_name = local_name;
2558 }
2559 
2560 le_command_status_t le_central_start_scan(){
2561     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2562     hci_stack->le_scanning_state = LE_START_SCAN;
2563     hci_run();
2564     return BLE_PERIPHERAL_OK;
2565 }
2566 
2567 le_command_status_t le_central_stop_scan(){
2568     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2569     hci_stack->le_scanning_state = LE_STOP_SCAN;
2570     hci_run();
2571     return BLE_PERIPHERAL_OK;
2572 }
2573 
2574 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2575     hci_stack->le_scan_type     = scan_type;
2576     hci_stack->le_scan_interval = scan_interval;
2577     hci_stack->le_scan_window   = scan_window;
2578     hci_run();
2579 }
2580 
2581 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2582     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2583     if (!conn){
2584         log_info("le_central_connect: no connection exists yet, creating context");
2585         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2586         if (!conn){
2587             // notify client that alloc failed
2588             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
2589             log_info("le_central_connect: failed to alloc hci_connection_t");
2590             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2591         }
2592         conn->state = SEND_CREATE_CONNECTION;
2593         log_info("le_central_connect: send create connection next");
2594         hci_run();
2595         return BLE_PERIPHERAL_OK;
2596     }
2597 
2598     if (!hci_is_le_connection(conn) ||
2599         conn->state == SEND_CREATE_CONNECTION ||
2600         conn->state == SENT_CREATE_CONNECTION) {
2601         hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
2602         log_error("le_central_connect: classic connection or connect is already being created");
2603         return BLE_PERIPHERAL_IN_WRONG_STATE;
2604     }
2605 
2606     log_info("le_central_connect: context exists with state %u", conn->state);
2607     hci_emit_le_connection_complete(conn->address_type, &conn->address, conn->con_handle, 0);
2608     hci_run();
2609     return BLE_PERIPHERAL_OK;
2610 }
2611 
2612 // @assumption: only a single outgoing LE Connection exists
2613 static hci_connection_t * le_central_get_outgoing_connection(){
2614     linked_item_t *it;
2615     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
2616         hci_connection_t * conn = (hci_connection_t *) it;
2617         if (!hci_is_le_connection(conn)) continue;
2618         switch (conn->state){
2619             case SEND_CREATE_CONNECTION:
2620             case SENT_CREATE_CONNECTION:
2621                 return conn;
2622             default:
2623                 break;
2624         };
2625     }
2626     return NULL;
2627 }
2628 
2629 le_command_status_t le_central_connect_cancel(){
2630     hci_connection_t * conn = le_central_get_outgoing_connection();
2631     switch (conn->state){
2632         case SEND_CREATE_CONNECTION:
2633             // skip sending create connection and emit event instead
2634             hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2635             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2636             btstack_memory_hci_connection_free( conn );
2637             break;
2638         case SENT_CREATE_CONNECTION:
2639             // request to send cancel connection
2640             conn->state = SEND_CANCEL_CONNECTION;
2641             hci_run();
2642             break;
2643         default:
2644             break;
2645     }
2646     return BLE_PERIPHERAL_OK;
2647 }
2648 
2649 /**
2650  * @brief Updates the connection parameters for a given LE connection
2651  * @param handle
2652  * @param conn_interval_min (unit: 1.25ms)
2653  * @param conn_interval_max (unit: 1.25ms)
2654  * @param conn_latency
2655  * @param supervision_timeout (unit: 10ms)
2656  * @returns 0 if ok
2657  */
2658 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2659     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2660     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2661     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2662     connection->le_conn_interval_min = conn_interval_min;
2663     connection->le_conn_interval_max = conn_interval_max;
2664     connection->le_conn_latency = conn_latency;
2665     connection->le_supervision_timeout = supervision_timeout;
2666     return 0;
2667 }
2668 
2669 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2670     hci_connection_t * conn = hci_connection_for_handle(handle);
2671     if (!conn){
2672         hci_emit_disconnection_complete(handle, 0);
2673         return BLE_PERIPHERAL_OK;
2674     }
2675     conn->state = SEND_DISCONNECT;
2676     hci_run();
2677     return BLE_PERIPHERAL_OK;
2678 }
2679 
2680 void hci_disconnect_all(){
2681     linked_list_iterator_t it;
2682     linked_list_iterator_init(&it, &hci_stack->connections);
2683     while (linked_list_iterator_has_next(&it)){
2684         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
2685         if (con->state == SENT_DISCONNECT) continue;
2686         con->state = SEND_DISCONNECT;
2687     }
2688     hci_run();
2689 }
2690