xref: /btstack/src/hci.c (revision c91d150bffd7d6a29578c50b4e882b0ac3adbb23)
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[2 + 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         uint8_t event_size = 10 + data_length;
733         int pos = 0;
734         event[pos++] = GAP_LE_ADVERTISING_REPORT;
735         event[pos++] = event_size;
736         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
737         offset += 8;
738         pos += 8;
739         event[pos++] = packet[offset + 1 + data_length]; // rssi
740         event[pos++] = packet[offset++]; //data_length;
741         memcpy(&event[pos], &packet[offset], data_length);
742         pos += data_length;
743         offset += data_length + 1; // rssi
744         hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
745         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
746     }
747 }
748 #endif
749 
750 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
751     uint8_t command_completed = 0;
752     if ((hci_stack->substate % 2) == 0) return;
753     // odd: waiting for event
754     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
755         uint16_t opcode = READ_BT_16(packet,3);
756         if (opcode == hci_stack->last_cmd_opcode){
757             command_completed = 1;
758             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate >> 1);
759         } else {
760             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
761         }
762     }
763     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
764         uint8_t  status = packet[2];
765         uint16_t opcode = READ_BT_16(packet,4);
766         if (opcode == hci_stack->last_cmd_opcode){
767             if (status){
768                 command_completed = 1;
769                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate >> 1);
770             } else {
771                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
772             }
773         } else {
774             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
775         }
776     }
777 
778     if (!command_completed) return;
779 
780     switch(hci_stack->substate >> 1){
781         default:
782             hci_stack->substate++;
783             break;
784     }
785 }
786 
787 static void hci_initializing_state_machine(){
788     if (hci_stack->substate % 2) {
789         // odd: waiting for command completion
790         return;
791     }
792     // log_info("hci_init: substate %u", hci_stack->substate >> 1);
793     switch (hci_stack->substate >> 1){
794         case 0: // RESET
795             hci_state_reset();
796 
797             hci_send_cmd(&hci_reset);
798             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
799                 // skip baud change
800                 hci_stack->substate = 2 << 1;
801             }
802             break;
803         case 1: // SEND BAUD CHANGE
804             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
805             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
806             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
807             break;
808         case 2: // LOCAL BAUD CHANGE
809             log_info("Local baud rate change");
810             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
811             hci_stack->substate += 2;
812             // break missing here for fall through
813 
814         case 3: // SET BD ADDR
815             if ( hci_stack->custom_bd_addr_set && hci_stack->control && hci_stack->control->set_bd_addr_cmd){
816                 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
817                 hci_stack->control->set_bd_addr_cmd(hci_stack->config, hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
818                 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
819                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
820                 break;
821             }
822             hci_stack->substate += 2;
823             // break missing here for fall through
824 
825         case 4:
826             log_info("Custom init");
827             // Custom initialization
828             if (hci_stack->control && hci_stack->control->next_cmd){
829                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
830                 if (valid_cmd){
831                     int size = 3 + hci_stack->hci_packet_buffer[2];
832                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
833                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
834                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
835                     hci_stack->substate = 3 << 1; // more init commands
836                     break;
837                 }
838                 log_info("hci_run: init script done");
839             }
840             // otherwise continue
841             hci_send_cmd(&hci_read_bd_addr);
842             break;
843         case 5:
844             hci_send_cmd(&hci_read_buffer_size);
845             break;
846         case 6:
847             hci_send_cmd(&hci_read_local_supported_features);
848             break;
849         case 7:
850             if (hci_le_supported()){
851                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
852             } else {
853                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
854                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
855             }
856 
857             // skip Classic init commands for LE only chipsets
858             if (!hci_classic_supported()){
859                 if (hci_le_supported()){
860                     hci_stack->substate = 12 << 1;    // skip all classic command
861                 } else {
862                     log_error("Neither BR/EDR nor LE supported");
863                     hci_stack->substate = 15 << 1;    // skip all
864                 }
865             }
866             break;
867         case 8:
868             if (hci_ssp_supported()){
869                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
870                 break;
871             }
872             hci_stack->substate += 2;
873             // break missing here for fall through
874 
875         case 9:
876             // ca. 15 sec
877             hci_send_cmd(&hci_write_page_timeout, 0x6000);
878             break;
879         case 10:
880             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
881             break;
882         case 11:
883             if (hci_stack->local_name){
884                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
885             } else {
886                 char hostname[30];
887 #ifdef EMBEDDED
888                 // BTstack-11:22:33:44:55:66
889                 strcpy(hostname, "BTstack ");
890                 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
891                 log_info("---> Name %s", hostname);
892 #else
893                 // hostname for POSIX systems
894                 gethostname(hostname, 30);
895                 hostname[29] = '\0';
896 #endif
897                 hci_send_cmd(&hci_write_local_name, hostname);
898             }
899             break;
900         case 12:
901             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
902             if (!hci_le_supported()){
903                 // SKIP LE init for Classic only configuration
904                 hci_stack->substate = 15 << 1;
905             }
906             break;
907 
908 #ifdef HAVE_BLE
909         // LE INIT
910         case 13:
911             hci_send_cmd(&hci_le_read_buffer_size);
912             break;
913         case 14:
914             // LE Supported Host = 1, Simultaneous Host = 0
915             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
916             break;
917         case 15:
918             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
919             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
920             break;
921 #endif
922 
923         // DONE
924         case 16:
925             // done.
926             hci_stack->state = HCI_STATE_WORKING;
927             hci_emit_state();
928             break;
929         default:
930             break;
931     }
932     hci_stack->substate++;
933 }
934 
935 // avoid huge local variables
936 #ifndef EMBEDDED
937 static device_name_t device_name;
938 #endif
939 static void event_handler(uint8_t *packet, int size){
940 
941     uint16_t event_length = packet[1];
942 
943     // assert packet is complete
944     if (size != event_length + 2){
945         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
946         return;
947     }
948 
949     bd_addr_t addr;
950     bd_addr_type_t addr_type;
951     uint8_t link_type;
952     hci_con_handle_t handle;
953     hci_connection_t * conn;
954     int i;
955 
956     // log_info("HCI:EVENT:%02x", packet[0]);
957 
958     switch (packet[0]) {
959 
960         case HCI_EVENT_COMMAND_COMPLETE:
961             // get num cmd packets
962             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
963             hci_stack->num_cmd_packets = packet[2];
964 
965             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
966                 // from offset 5
967                 // status
968                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
969                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
970                 // ignore: SCO data packet len (8)
971                 hci_stack->acl_packets_total_num  = packet[9];
972                 // ignore: total num SCO packets
973                 if (hci_stack->state == HCI_STATE_INITIALIZING){
974                     // determine usable ACL payload size
975                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
976                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
977                     }
978                     log_info("hci_read_buffer_size: used size %u, count %u",
979                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num);
980                 }
981             }
982 #ifdef HAVE_BLE
983             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
984                 hci_stack->le_data_packets_length = READ_BT_16(packet, 6);
985                 hci_stack->le_acl_packets_total_num  = packet[8];
986                     // determine usable ACL payload size
987                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
988                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
989                     }
990                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
991             }
992 #endif
993             // Dump local address
994             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
995                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
996                 log_info("Local Address, Status: 0x%02x: Addr: %s",
997                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
998             }
999             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1000                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1001             }
1002             // Note: HCI init checks
1003             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
1004                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1005                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
1006                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
1007                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
1008                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
1009                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
1010 
1011                 // determine usable ACL packet types based on host buffer size and supported features
1012                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1013                 log_info("packet types %04x", hci_stack->packet_types);
1014 
1015                 // Classic/LE
1016                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1017             }
1018             break;
1019 
1020         case HCI_EVENT_COMMAND_STATUS:
1021             // get num cmd packets
1022             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
1023             hci_stack->num_cmd_packets = packet[3];
1024             break;
1025 
1026         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1027             int offset = 3;
1028             for (i=0; i<packet[2];i++){
1029                 handle = READ_BT_16(packet, offset);
1030                 offset += 2;
1031                 uint16_t num_packets = READ_BT_16(packet, offset);
1032                 offset += 2;
1033 
1034                 conn = hci_connection_for_handle(handle);
1035                 if (!conn){
1036                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1037                     continue;
1038                 }
1039 
1040                 if (conn->num_acl_packets_sent >= num_packets){
1041                     conn->num_acl_packets_sent -= num_packets;
1042                 } else {
1043                     log_error("hci_number_completed_packets, more slots freed then sent.");
1044                     conn->num_acl_packets_sent = 0;
1045                 }
1046                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1047             }
1048             break;
1049         }
1050         case HCI_EVENT_CONNECTION_REQUEST:
1051             bt_flip_addr(addr, &packet[2]);
1052             // TODO: eval COD 8-10
1053             link_type = packet[11];
1054             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1055             if (link_type == 1) { // ACL
1056                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1057                 if (!conn) {
1058                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1059                 }
1060                 if (!conn) {
1061                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1062                     hci_stack->decline_reason = 0x0d;
1063                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
1064                     break;
1065                 }
1066                 conn->state = RECEIVED_CONNECTION_REQUEST;
1067                 hci_run();
1068             } else {
1069                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
1070                 hci_stack->decline_reason = 0x0a;
1071                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
1072             }
1073             break;
1074 
1075         case HCI_EVENT_CONNECTION_COMPLETE:
1076             // Connection management
1077             bt_flip_addr(addr, &packet[5]);
1078             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1079             addr_type = BD_ADDR_TYPE_CLASSIC;
1080             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1081             if (conn) {
1082                 if (!packet[2]){
1083                     conn->state = OPEN;
1084                     conn->con_handle = READ_BT_16(packet, 3);
1085                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1086 
1087                     // restart timer
1088                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1089                     run_loop_add_timer(&conn->timeout);
1090 
1091                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1092 
1093                     hci_emit_nr_connections_changed();
1094                 } else {
1095                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1096                     uint8_t status = packet[2];
1097                     bd_addr_t bd_address;
1098                     memcpy(&bd_address, conn->address, 6);
1099 
1100                     // connection failed, remove entry
1101                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1102                     btstack_memory_hci_connection_free( conn );
1103 
1104                     // notify client if dedicated bonding
1105                     if (notify_dedicated_bonding_failed){
1106                         log_info("hci notify_dedicated_bonding_failed");
1107                         hci_emit_dedicated_bonding_result(bd_address, status);
1108                     }
1109 
1110                     // if authentication error, also delete link key
1111                     if (packet[2] == 0x05) {
1112                         hci_drop_link_key_for_bd_addr(&addr);
1113                     }
1114                 }
1115             }
1116             break;
1117 
1118         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1119             handle = READ_BT_16(packet, 3);
1120             conn = hci_connection_for_handle(handle);
1121             if (!conn) break;
1122             if (!packet[2]){
1123                 uint8_t * features = &packet[5];
1124                 if (features[6] & (1 << 3)){
1125                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1126                 }
1127             }
1128             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1129             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1130             if (conn->bonding_flags & BONDING_DEDICATED){
1131                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1132             }
1133             break;
1134 
1135         case HCI_EVENT_LINK_KEY_REQUEST:
1136             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1137             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1138             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1139             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
1140             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1141             hci_run();
1142             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1143             return;
1144 
1145         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1146             bt_flip_addr(addr, &packet[2]);
1147             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1148             if (!conn) break;
1149             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1150             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1151             // Change Connection Encryption keeps link key type
1152             if (link_key_type != CHANGED_COMBINATION_KEY){
1153                 conn->link_key_type = link_key_type;
1154             }
1155             if (!hci_stack->remote_device_db) break;
1156             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
1157             // still forward event to allow dismiss of pairing dialog
1158             break;
1159         }
1160 
1161         case HCI_EVENT_PIN_CODE_REQUEST:
1162             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1163             // non-bondable mode: pin code negative reply will be sent
1164             if (!hci_stack->bondable){
1165                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1166                 hci_run();
1167                 return;
1168             }
1169             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1170             if (!hci_stack->remote_device_db) break;
1171             bt_flip_addr(addr, &packet[2]);
1172             hci_stack->remote_device_db->delete_link_key(&addr);
1173             break;
1174 
1175         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1176             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1177             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1178             break;
1179 
1180         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1181             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1182             if (!hci_stack->ssp_auto_accept) break;
1183             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1184             break;
1185 
1186         case HCI_EVENT_USER_PASSKEY_REQUEST:
1187             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1188             if (!hci_stack->ssp_auto_accept) break;
1189             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1190             break;
1191 
1192         case HCI_EVENT_ENCRYPTION_CHANGE:
1193             handle = READ_BT_16(packet, 3);
1194             conn = hci_connection_for_handle(handle);
1195             if (!conn) break;
1196             if (packet[2] == 0) {
1197                 if (packet[5]){
1198                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1199                 } else {
1200                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1201                 }
1202             }
1203             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1204             break;
1205 
1206         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1207             handle = READ_BT_16(packet, 3);
1208             conn = hci_connection_for_handle(handle);
1209             if (!conn) break;
1210 
1211             // dedicated bonding: send result and disconnect
1212             if (conn->bonding_flags & BONDING_DEDICATED){
1213                 conn->bonding_flags &= ~BONDING_DEDICATED;
1214                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1215                 conn->bonding_status = packet[2];
1216                 break;
1217             }
1218 
1219             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1220                 // link key sufficient for requested security
1221                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1222                 break;
1223             }
1224             // not enough
1225             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1226             break;
1227 
1228 #ifndef EMBEDDED
1229         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1230             if (!hci_stack->remote_device_db) break;
1231             if (packet[2]) break; // status not ok
1232             bt_flip_addr(addr, &packet[3]);
1233             // fix for invalid remote names - terminate on 0xff
1234             for (i=0; i<248;i++){
1235                 if (packet[9+i] == 0xff){
1236                     packet[9+i] = 0;
1237                     break;
1238                 }
1239             }
1240             memset(&device_name, 0, sizeof(device_name_t));
1241             strncpy((char*) device_name, (char*) &packet[9], 248);
1242             hci_stack->remote_device_db->put_name(&addr, &device_name);
1243             break;
1244 
1245         case HCI_EVENT_INQUIRY_RESULT:
1246         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
1247             if (!hci_stack->remote_device_db) break;
1248             // first send inq result packet
1249             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1250             // then send cached remote names
1251             int offset = 3;
1252             for (i=0; i<packet[2];i++){
1253                 bt_flip_addr(addr, &packet[offset]);
1254                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
1255                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
1256                     hci_emit_remote_name_cached(&addr, &device_name);
1257                 }
1258             }
1259             return;
1260         }
1261 #endif
1262 
1263         // HCI_EVENT_DISCONNECTION_COMPLETE
1264         // has been split, to first notify stack before shutting connection down
1265         // see end of function, too.
1266         case HCI_EVENT_DISCONNECTION_COMPLETE:
1267             if (packet[2]) break;   // status != 0
1268             handle = READ_BT_16(packet, 3);
1269             hci_connection_t * conn = hci_connection_for_handle(handle);
1270             if (!conn) break;       // no conn struct anymore
1271             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1272             break;
1273 
1274         case HCI_EVENT_HARDWARE_ERROR:
1275             if(hci_stack->control && hci_stack->control->hw_error){
1276                 (*hci_stack->control->hw_error)();
1277             } else {
1278                 // if no special requests, just reboot stack
1279                 hci_power_control_off();
1280                 hci_power_control_on();
1281             }
1282             break;
1283 
1284         case DAEMON_EVENT_HCI_PACKET_SENT:
1285             // release packet buffer only for asynchronous transport and if there are not further fragements
1286             if (hci_transport_synchronous()) {
1287                 log_error("Synchronous HCI Transport shouldn't send DAEMON_EVENT_HCI_PACKET_SENT");
1288                 return; // instead of break: to avoid re-entering hci_run()
1289             }
1290             if (hci_stack->acl_fragmentation_total_size) break;
1291             hci_release_packet_buffer();
1292             break;
1293 
1294 #ifdef HAVE_BLE
1295         case HCI_EVENT_LE_META:
1296             switch (packet[2]){
1297                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1298                     log_info("advertising report received");
1299                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1300                     le_handle_advertisement_report(packet, size);
1301                     break;
1302                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1303                     // Connection management
1304                     bt_flip_addr(addr, &packet[8]);
1305                     addr_type = (bd_addr_type_t)packet[7];
1306                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1307                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1308                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1309                     if (packet[3]){
1310                         if (conn){
1311                             // outgoing connection failed, remove entry
1312                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1313                             btstack_memory_hci_connection_free( conn );
1314                         }
1315                         // if authentication error, also delete link key
1316                         if (packet[3] == 0x05) {
1317                             hci_drop_link_key_for_bd_addr(&addr);
1318                         }
1319                         break;
1320                     }
1321                     if (!conn){
1322                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1323                     }
1324                     if (!conn){
1325                         // no memory
1326                         break;
1327                     }
1328 
1329                     conn->state = OPEN;
1330                     conn->con_handle = READ_BT_16(packet, 4);
1331 
1332                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1333 
1334                     // restart timer
1335                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1336                     // run_loop_add_timer(&conn->timeout);
1337 
1338                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1339 
1340                     hci_emit_nr_connections_changed();
1341                     break;
1342 
1343             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
1344 
1345                 default:
1346                     break;
1347             }
1348             break;
1349 #endif
1350         default:
1351             break;
1352     }
1353 
1354     // handle BT initialization
1355     if (hci_stack->state == HCI_STATE_INITIALIZING){
1356         hci_initializing_event_handler(packet, size);
1357     }
1358 
1359     // help with BT sleep
1360     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1361         && hci_stack->substate == 1
1362         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1363         hci_stack->substate++;
1364     }
1365 
1366     // notify upper stack
1367     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1368 
1369     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1370     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1371         if (!packet[2]){
1372             handle = READ_BT_16(packet, 3);
1373             hci_connection_t * conn = hci_connection_for_handle(handle);
1374             if (conn) {
1375                 uint8_t status = conn->bonding_status;
1376                 uint16_t flags = conn->bonding_flags;
1377                 bd_addr_t bd_address;
1378                 memcpy(&bd_address, conn->address, 6);
1379                 hci_shutdown_connection(conn);
1380                 // connection struct is gone, don't access anymore
1381                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1382                     hci_emit_dedicated_bonding_result(bd_address, status);
1383                 }
1384             }
1385         }
1386     }
1387 
1388 	// execute main loop
1389 	hci_run();
1390 }
1391 
1392 static void sco_handler(uint8_t * packet, uint16_t size){
1393     // not handled yet
1394 }
1395 
1396 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1397     hci_dump_packet(packet_type, 1, packet, size);
1398     switch (packet_type) {
1399         case HCI_EVENT_PACKET:
1400             event_handler(packet, size);
1401             break;
1402         case HCI_ACL_DATA_PACKET:
1403             acl_handler(packet, size);
1404             break;
1405         case HCI_SCO_DATA_PACKET:
1406             sco_handler(packet, size);
1407         default:
1408             break;
1409     }
1410 }
1411 
1412 /** Register HCI packet handlers */
1413 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1414     hci_stack->packet_handler = handler;
1415 }
1416 
1417 static void hci_state_reset(){
1418     // no connections yet
1419     hci_stack->connections = NULL;
1420 
1421     // keep discoverable/connectable as this has been requested by the client(s)
1422     // hci_stack->discoverable = 0;
1423     // hci_stack->connectable = 0;
1424     // hci_stack->bondable = 1;
1425 
1426     // buffer is free
1427     hci_stack->hci_packet_buffer_reserved = 0;
1428 
1429     // no pending cmds
1430     hci_stack->decline_reason = 0;
1431     hci_stack->new_scan_enable_value = 0xff;
1432 
1433     // LE
1434     hci_stack->adv_addr_type = 0;
1435     memset(hci_stack->adv_address, 0, 6);
1436     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1437     hci_stack->le_scan_type = 0xff;
1438     hci_stack->le_connection_parameter_range.le_conn_interval_min = 0x0006;
1439     hci_stack->le_connection_parameter_range.le_conn_interval_max = 0x0C80;
1440     hci_stack->le_connection_parameter_range.le_conn_latency_min = 0x0000;
1441     hci_stack->le_connection_parameter_range.le_conn_latency_max = 0x03E8;
1442     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 0x000A;
1443     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 0x0C80;
1444 }
1445 
1446 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1447 
1448 #ifdef HAVE_MALLOC
1449     if (!hci_stack) {
1450         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1451     }
1452 #else
1453     hci_stack = &hci_stack_static;
1454 #endif
1455     memset(hci_stack, 0, sizeof(hci_stack_t));
1456 
1457     // reference to use transport layer implementation
1458     hci_stack->hci_transport = transport;
1459 
1460     // references to used control implementation
1461     hci_stack->control = control;
1462 
1463     // reference to used config
1464     hci_stack->config = config;
1465 
1466     // higher level handler
1467     hci_stack->packet_handler = dummy_handler;
1468 
1469     // store and open remote device db
1470     hci_stack->remote_device_db = remote_device_db;
1471     if (hci_stack->remote_device_db) {
1472         hci_stack->remote_device_db->open();
1473     }
1474 
1475     // max acl payload size defined in config.h
1476     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1477 
1478     // register packet handlers with transport
1479     transport->register_packet_handler(&packet_handler);
1480 
1481     hci_stack->state = HCI_STATE_OFF;
1482 
1483     // class of device
1484     hci_stack->class_of_device = 0x007a020c; // Smartphone
1485 
1486     // bondable by default
1487     hci_stack->bondable = 1;
1488 
1489     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1490     hci_stack->ssp_enable = 1;
1491     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1492     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1493     hci_stack->ssp_auto_accept = 1;
1494 
1495     hci_state_reset();
1496 }
1497 
1498 void hci_close(){
1499     // close remote device db
1500     if (hci_stack->remote_device_db) {
1501         hci_stack->remote_device_db->close();
1502     }
1503     while (hci_stack->connections) {
1504         // cancel all l2cap connections
1505         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1506         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1507     }
1508     hci_power_control(HCI_POWER_OFF);
1509 
1510 #ifdef HAVE_MALLOC
1511     free(hci_stack);
1512 #endif
1513     hci_stack = NULL;
1514 }
1515 
1516 void hci_set_class_of_device(uint32_t class_of_device){
1517     hci_stack->class_of_device = class_of_device;
1518 }
1519 
1520 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
1521 void hci_set_bd_addr(bd_addr_t addr){
1522     memcpy(hci_stack->custom_bd_addr, addr, 6);
1523     hci_stack->custom_bd_addr_set = 1;
1524 }
1525 
1526 void hci_disable_l2cap_timeout_check(){
1527     disable_l2cap_timeouts = 1;
1528 }
1529 // State-Module-Driver overview
1530 // state                    module  low-level
1531 // HCI_STATE_OFF             off      close
1532 // HCI_STATE_INITIALIZING,   on       open
1533 // HCI_STATE_WORKING,        on       open
1534 // HCI_STATE_HALTING,        on       open
1535 // HCI_STATE_SLEEPING,    off/sleep   close
1536 // HCI_STATE_FALLING_ASLEEP  on       open
1537 
1538 static int hci_power_control_on(void){
1539 
1540     // power on
1541     int err = 0;
1542     if (hci_stack->control && hci_stack->control->on){
1543         err = (*hci_stack->control->on)(hci_stack->config);
1544     }
1545     if (err){
1546         log_error( "POWER_ON failed");
1547         hci_emit_hci_open_failed();
1548         return err;
1549     }
1550 
1551     // open low-level device
1552     err = hci_stack->hci_transport->open(hci_stack->config);
1553     if (err){
1554         log_error( "HCI_INIT failed, turning Bluetooth off again");
1555         if (hci_stack->control && hci_stack->control->off){
1556             (*hci_stack->control->off)(hci_stack->config);
1557         }
1558         hci_emit_hci_open_failed();
1559         return err;
1560     }
1561     return 0;
1562 }
1563 
1564 static void hci_power_control_off(void){
1565 
1566     log_info("hci_power_control_off");
1567 
1568     // close low-level device
1569     hci_stack->hci_transport->close(hci_stack->config);
1570 
1571     log_info("hci_power_control_off - hci_transport closed");
1572 
1573     // power off
1574     if (hci_stack->control && hci_stack->control->off){
1575         (*hci_stack->control->off)(hci_stack->config);
1576     }
1577 
1578     log_info("hci_power_control_off - control closed");
1579 
1580     hci_stack->state = HCI_STATE_OFF;
1581 }
1582 
1583 static void hci_power_control_sleep(void){
1584 
1585     log_info("hci_power_control_sleep");
1586 
1587 #if 0
1588     // don't close serial port during sleep
1589 
1590     // close low-level device
1591     hci_stack->hci_transport->close(hci_stack->config);
1592 #endif
1593 
1594     // sleep mode
1595     if (hci_stack->control && hci_stack->control->sleep){
1596         (*hci_stack->control->sleep)(hci_stack->config);
1597     }
1598 
1599     hci_stack->state = HCI_STATE_SLEEPING;
1600 }
1601 
1602 static int hci_power_control_wake(void){
1603 
1604     log_info("hci_power_control_wake");
1605 
1606     // wake on
1607     if (hci_stack->control && hci_stack->control->wake){
1608         (*hci_stack->control->wake)(hci_stack->config);
1609     }
1610 
1611 #if 0
1612     // open low-level device
1613     int err = hci_stack->hci_transport->open(hci_stack->config);
1614     if (err){
1615         log_error( "HCI_INIT failed, turning Bluetooth off again");
1616         if (hci_stack->control && hci_stack->control->off){
1617             (*hci_stack->control->off)(hci_stack->config);
1618         }
1619         hci_emit_hci_open_failed();
1620         return err;
1621     }
1622 #endif
1623 
1624     return 0;
1625 }
1626 
1627 static void hci_power_transition_to_initializing(void){
1628     // set up state machine
1629     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1630     hci_stack->hci_packet_buffer_reserved = 0;
1631     hci_stack->state = HCI_STATE_INITIALIZING;
1632     hci_stack->substate = 0;
1633 }
1634 
1635 int hci_power_control(HCI_POWER_MODE power_mode){
1636 
1637     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1638 
1639     int err = 0;
1640     switch (hci_stack->state){
1641 
1642         case HCI_STATE_OFF:
1643             switch (power_mode){
1644                 case HCI_POWER_ON:
1645                     err = hci_power_control_on();
1646                     if (err) {
1647                         log_error("hci_power_control_on() error %u", err);
1648                         return err;
1649                     }
1650                     hci_power_transition_to_initializing();
1651                     break;
1652                 case HCI_POWER_OFF:
1653                     // do nothing
1654                     break;
1655                 case HCI_POWER_SLEEP:
1656                     // do nothing (with SLEEP == OFF)
1657                     break;
1658             }
1659             break;
1660 
1661         case HCI_STATE_INITIALIZING:
1662             switch (power_mode){
1663                 case HCI_POWER_ON:
1664                     // do nothing
1665                     break;
1666                 case HCI_POWER_OFF:
1667                     // no connections yet, just turn it off
1668                     hci_power_control_off();
1669                     break;
1670                 case HCI_POWER_SLEEP:
1671                     // no connections yet, just turn it off
1672                     hci_power_control_sleep();
1673                     break;
1674             }
1675             break;
1676 
1677         case HCI_STATE_WORKING:
1678             switch (power_mode){
1679                 case HCI_POWER_ON:
1680                     // do nothing
1681                     break;
1682                 case HCI_POWER_OFF:
1683                     // see hci_run
1684                     hci_stack->state = HCI_STATE_HALTING;
1685                     break;
1686                 case HCI_POWER_SLEEP:
1687                     // see hci_run
1688                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1689                     hci_stack->substate = 0;
1690                     break;
1691             }
1692             break;
1693 
1694         case HCI_STATE_HALTING:
1695             switch (power_mode){
1696                 case HCI_POWER_ON:
1697                     hci_power_transition_to_initializing();
1698                     break;
1699                 case HCI_POWER_OFF:
1700                     // do nothing
1701                     break;
1702                 case HCI_POWER_SLEEP:
1703                     // see hci_run
1704                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1705                     hci_stack->substate = 0;
1706                     break;
1707             }
1708             break;
1709 
1710         case HCI_STATE_FALLING_ASLEEP:
1711             switch (power_mode){
1712                 case HCI_POWER_ON:
1713 
1714 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1715                     // nothing to do, if H4 supports power management
1716                     if (bt_control_iphone_power_management_enabled()){
1717                         hci_stack->state = HCI_STATE_INITIALIZING;
1718                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1719                         break;
1720                     }
1721 #endif
1722                     hci_power_transition_to_initializing();
1723                     break;
1724                 case HCI_POWER_OFF:
1725                     // see hci_run
1726                     hci_stack->state = HCI_STATE_HALTING;
1727                     break;
1728                 case HCI_POWER_SLEEP:
1729                     // do nothing
1730                     break;
1731             }
1732             break;
1733 
1734         case HCI_STATE_SLEEPING:
1735             switch (power_mode){
1736                 case HCI_POWER_ON:
1737 
1738 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1739                     // nothing to do, if H4 supports power management
1740                     if (bt_control_iphone_power_management_enabled()){
1741                         hci_stack->state = HCI_STATE_INITIALIZING;
1742                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1743                         hci_update_scan_enable();
1744                         break;
1745                     }
1746 #endif
1747                     err = hci_power_control_wake();
1748                     if (err) return err;
1749                     hci_power_transition_to_initializing();
1750                     break;
1751                 case HCI_POWER_OFF:
1752                     hci_stack->state = HCI_STATE_HALTING;
1753                     break;
1754                 case HCI_POWER_SLEEP:
1755                     // do nothing
1756                     break;
1757             }
1758             break;
1759     }
1760 
1761     // create internal event
1762 	hci_emit_state();
1763 
1764 	// trigger next/first action
1765 	hci_run();
1766 
1767     return 0;
1768 }
1769 
1770 static void hci_update_scan_enable(void){
1771     // 2 = page scan, 1 = inq scan
1772     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1773     hci_run();
1774 }
1775 
1776 void hci_discoverable_control(uint8_t enable){
1777     if (enable) enable = 1; // normalize argument
1778 
1779     if (hci_stack->discoverable == enable){
1780         hci_emit_discoverable_enabled(hci_stack->discoverable);
1781         return;
1782     }
1783 
1784     hci_stack->discoverable = enable;
1785     hci_update_scan_enable();
1786 }
1787 
1788 void hci_connectable_control(uint8_t enable){
1789     if (enable) enable = 1; // normalize argument
1790 
1791     // don't emit event
1792     if (hci_stack->connectable == enable) return;
1793 
1794     hci_stack->connectable = enable;
1795     hci_update_scan_enable();
1796 }
1797 
1798 bd_addr_t * hci_local_bd_addr(void){
1799     return &hci_stack->local_bd_addr;
1800 }
1801 
1802 void hci_run(){
1803 
1804     hci_connection_t * connection;
1805     linked_item_t * it;
1806 
1807     // send continuation fragments first, as they block the prepared packet buffer
1808     if (hci_stack->acl_fragmentation_total_size > 0) {
1809         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1810         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1811             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1812             if (connection) {
1813                 hci_send_acl_packet_fragments(connection);
1814                 return;
1815             }
1816             // connection gone -> discard further fragments
1817             hci_stack->acl_fragmentation_total_size = 0;
1818             hci_stack->acl_fragmentation_pos = 0;
1819         }
1820     }
1821 
1822     if (!hci_can_send_command_packet_now()) return;
1823 
1824     // global/non-connection oriented commands
1825 
1826     // decline incoming connections
1827     if (hci_stack->decline_reason){
1828         uint8_t reason = hci_stack->decline_reason;
1829         hci_stack->decline_reason = 0;
1830         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1831         return;
1832     }
1833 
1834     // send scan enable
1835     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1836         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1837         hci_stack->new_scan_enable_value = 0xff;
1838         return;
1839     }
1840 
1841 #ifdef HAVE_BLE
1842     // handle le scan
1843     if (hci_stack->state == HCI_STATE_WORKING){
1844         switch(hci_stack->le_scanning_state){
1845             case LE_START_SCAN:
1846                 hci_stack->le_scanning_state = LE_SCANNING;
1847                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1848                 return;
1849 
1850             case LE_STOP_SCAN:
1851                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1852                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1853                 return;
1854             default:
1855                 break;
1856         }
1857         if (hci_stack->le_scan_type != 0xff){
1858             // defaults: active scanning, accept all advertisement packets
1859             int scan_type = hci_stack->le_scan_type;
1860             hci_stack->le_scan_type = 0xff;
1861             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);
1862             return;
1863         }
1864     }
1865 #endif
1866 
1867     // send pending HCI commands
1868     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1869         connection = (hci_connection_t *) it;
1870 
1871         switch(connection->state){
1872             case SEND_CREATE_CONNECTION:
1873                 switch(connection->address_type){
1874                     case BD_ADDR_TYPE_CLASSIC:
1875                         log_info("sending hci_create_connection");
1876                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1877                         break;
1878                     default:
1879 #ifdef HAVE_BLE
1880                         log_info("sending hci_le_create_connection");
1881                         hci_send_cmd(&hci_le_create_connection,
1882                                      0x0060,    // scan interval: 60 ms
1883                                      0x0030,    // scan interval: 30 ms
1884                                      0,         // don't use whitelist
1885                                      connection->address_type, // peer address type
1886                                      connection->address,      // peer bd addr
1887                                      hci_stack->adv_addr_type, // our addr type:
1888                                      0x0008,    // conn interval min
1889                                      0x0018,    // conn interval max
1890                                      0,         // conn latency
1891                                      0x0048,    // supervision timeout
1892                                      0x0001,    // min ce length
1893                                      0x0001     // max ce length
1894                                      );
1895 
1896                         connection->state = SENT_CREATE_CONNECTION;
1897 #endif
1898                         break;
1899                 }
1900                 return;
1901 
1902             case RECEIVED_CONNECTION_REQUEST:
1903                 log_info("sending hci_accept_connection_request");
1904                 connection->state = ACCEPTED_CONNECTION_REQUEST;
1905                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1906                 return;
1907 
1908 #ifdef HAVE_BLE
1909             case SEND_CANCEL_CONNECTION:
1910                 connection->state = SENT_CANCEL_CONNECTION;
1911                 hci_send_cmd(&hci_le_create_connection_cancel);
1912                 return;
1913 #endif
1914             case SEND_DISCONNECT:
1915                 connection->state = SENT_DISCONNECT;
1916                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1917                 return;
1918 
1919             default:
1920                 break;
1921         }
1922 
1923         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1924             log_info("responding to link key request");
1925             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1926             link_key_t link_key;
1927             link_key_type_t link_key_type;
1928             if ( hci_stack->remote_device_db
1929               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1930               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1931                connection->link_key_type = link_key_type;
1932                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1933             } else {
1934                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1935             }
1936             return;
1937         }
1938 
1939         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1940             log_info("denying to pin request");
1941             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1942             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1943             return;
1944         }
1945 
1946         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1947             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1948             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1949             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1950                 // tweak authentication requirements
1951                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1952                 if (connection->bonding_flags & BONDING_DEDICATED){
1953                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1954                 }
1955                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1956                     authreq |= 1;
1957                 }
1958                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1959             } else {
1960                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1961             }
1962             return;
1963         }
1964 
1965         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1966             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1967             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1968             return;
1969         }
1970 
1971         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1972             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1973             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1974             return;
1975         }
1976 
1977         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1978             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1979             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1980             return;
1981         }
1982 
1983         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1984             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1985             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1986             return;
1987         }
1988         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1989             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1990             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
1991             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1992             return;
1993         }
1994         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1995             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1996             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1997             return;
1998         }
1999         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2000             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2001             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2002             return;
2003         }
2004 
2005 #ifdef HAVE_BLE
2006         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2007             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2008 
2009             uint16_t connection_interval_min = connection->le_conn_interval_min;
2010             connection->le_conn_interval_min = 0;
2011             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2012                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2013                 0x0000, 0xffff);
2014         }
2015 #endif
2016     }
2017 
2018     switch (hci_stack->state){
2019         case HCI_STATE_INITIALIZING:
2020             hci_initializing_state_machine();
2021             break;
2022 
2023         case HCI_STATE_HALTING:
2024 
2025             log_info("HCI_STATE_HALTING");
2026             // close all open connections
2027             connection =  (hci_connection_t *) hci_stack->connections;
2028             if (connection){
2029 
2030                 // send disconnect
2031                 if (!hci_can_send_command_packet_now()) return;
2032 
2033                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2034                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2035 
2036                 // send disconnected event right away - causes higher layer connections to get closed, too.
2037                 hci_shutdown_connection(connection);
2038                 return;
2039             }
2040             log_info("HCI_STATE_HALTING, calling off");
2041 
2042             // switch mode
2043             hci_power_control_off();
2044 
2045             log_info("HCI_STATE_HALTING, emitting state");
2046             hci_emit_state();
2047             log_info("HCI_STATE_HALTING, done");
2048             break;
2049 
2050         case HCI_STATE_FALLING_ASLEEP:
2051             switch(hci_stack->substate) {
2052                 case 0:
2053                     log_info("HCI_STATE_FALLING_ASLEEP");
2054                     // close all open connections
2055                     connection =  (hci_connection_t *) hci_stack->connections;
2056 
2057 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2058                     // don't close connections, if H4 supports power management
2059                     if (bt_control_iphone_power_management_enabled()){
2060                         connection = NULL;
2061                     }
2062 #endif
2063                     if (connection){
2064 
2065                         // send disconnect
2066                         if (!hci_can_send_command_packet_now()) return;
2067 
2068                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2069                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2070 
2071                         // send disconnected event right away - causes higher layer connections to get closed, too.
2072                         hci_shutdown_connection(connection);
2073                         return;
2074                     }
2075 
2076                     if (hci_classic_supported()){
2077                         // disable page and inquiry scan
2078                         if (!hci_can_send_command_packet_now()) return;
2079 
2080                         log_info("HCI_STATE_HALTING, disabling inq scans");
2081                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
2082 
2083                         // continue in next sub state
2084                         hci_stack->substate++;
2085                         break;
2086                     }
2087                     // fall through for ble-only chips
2088 
2089                 case 2:
2090                     log_info("HCI_STATE_HALTING, calling sleep");
2091 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2092                     // don't actually go to sleep, if H4 supports power management
2093                     if (bt_control_iphone_power_management_enabled()){
2094                         // SLEEP MODE reached
2095                         hci_stack->state = HCI_STATE_SLEEPING;
2096                         hci_emit_state();
2097                         break;
2098                     }
2099 #endif
2100                     // switch mode
2101                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2102                     hci_emit_state();
2103                     break;
2104 
2105                 default:
2106                     break;
2107             }
2108             break;
2109 
2110         default:
2111             break;
2112     }
2113 }
2114 
2115 int hci_send_cmd_packet(uint8_t *packet, int size){
2116     bd_addr_t addr;
2117     hci_connection_t * conn;
2118     // house-keeping
2119 
2120     // create_connection?
2121     if (IS_COMMAND(packet, hci_create_connection)){
2122         bt_flip_addr(addr, &packet[3]);
2123         log_info("Create_connection to %s", bd_addr_to_str(addr));
2124 
2125         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2126         if (!conn){
2127             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2128             if (!conn){
2129                 // notify client that alloc failed
2130                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2131                 return 0; // don't sent packet to controller
2132             }
2133             conn->state = SEND_CREATE_CONNECTION;
2134         }
2135         log_info("conn state %u", conn->state);
2136         switch (conn->state){
2137             // if connection active exists
2138             case OPEN:
2139                 // and OPEN, emit connection complete command, don't send to controller
2140                 hci_emit_connection_complete(conn, 0);
2141                 return 0;
2142             case SEND_CREATE_CONNECTION:
2143                 // connection created by hci, e.g. dedicated bonding
2144                 break;
2145             default:
2146                 // otherwise, just ignore as it is already in the open process
2147                 return 0;
2148         }
2149         conn->state = SENT_CREATE_CONNECTION;
2150     }
2151 
2152     if (IS_COMMAND(packet, hci_link_key_request_reply)){
2153         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
2154     }
2155     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
2156         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
2157     }
2158 
2159     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2160         if (hci_stack->remote_device_db){
2161             bt_flip_addr(addr, &packet[3]);
2162             hci_stack->remote_device_db->delete_link_key(&addr);
2163         }
2164     }
2165 
2166     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2167     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2168         bt_flip_addr(addr, &packet[3]);
2169         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2170         if (conn){
2171             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2172         }
2173     }
2174 
2175     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2176     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2177     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2178     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2179         bt_flip_addr(addr, &packet[3]);
2180         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2181         if (conn){
2182             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2183         }
2184     }
2185 
2186 #ifdef HAVE_BLE
2187     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2188         hci_stack->adv_addr_type = packet[8];
2189     }
2190     if (IS_COMMAND(packet, hci_le_set_random_address)){
2191         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2192     }
2193 #endif
2194 
2195     hci_stack->num_cmd_packets--;
2196 
2197     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2198     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2199 
2200     // release packet buffer for synchronous transport implementations
2201     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2202         hci_stack->hci_packet_buffer_reserved = 0;
2203     }
2204 
2205     return err;
2206 }
2207 
2208 // disconnect because of security block
2209 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2210     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2211     if (!connection) return;
2212     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2213 }
2214 
2215 
2216 // Configure Secure Simple Pairing
2217 
2218 // enable will enable SSP during init
2219 void hci_ssp_set_enable(int enable){
2220     hci_stack->ssp_enable = enable;
2221 }
2222 
2223 int hci_local_ssp_activated(){
2224     return hci_ssp_supported() && hci_stack->ssp_enable;
2225 }
2226 
2227 // if set, BTstack will respond to io capability request using authentication requirement
2228 void hci_ssp_set_io_capability(int io_capability){
2229     hci_stack->ssp_io_capability = io_capability;
2230 }
2231 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2232     hci_stack->ssp_authentication_requirement = authentication_requirement;
2233 }
2234 
2235 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2236 void hci_ssp_set_auto_accept(int auto_accept){
2237     hci_stack->ssp_auto_accept = auto_accept;
2238 }
2239 
2240 /**
2241  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2242  */
2243 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2244 
2245     if (!hci_can_send_command_packet_now()){
2246         log_error("hci_send_cmd called but cannot send packet now");
2247         return 0;
2248     }
2249 
2250     // for HCI INITIALIZATION
2251     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2252     hci_stack->last_cmd_opcode = cmd->opcode;
2253 
2254     hci_reserve_packet_buffer();
2255     uint8_t * packet = hci_stack->hci_packet_buffer;
2256 
2257     va_list argptr;
2258     va_start(argptr, cmd);
2259     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
2260     va_end(argptr);
2261 
2262     return hci_send_cmd_packet(packet, size);
2263 }
2264 
2265 // Create various non-HCI events.
2266 // TODO: generalize, use table similar to hci_create_command
2267 
2268 void hci_emit_state(){
2269     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2270     uint8_t event[3];
2271     event[0] = BTSTACK_EVENT_STATE;
2272     event[1] = sizeof(event) - 2;
2273     event[2] = hci_stack->state;
2274     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2275     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2276 }
2277 
2278 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2279     uint8_t event[13];
2280     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2281     event[1] = sizeof(event) - 2;
2282     event[2] = status;
2283     bt_store_16(event, 3, conn->con_handle);
2284     bt_flip_addr(&event[5], conn->address);
2285     event[11] = 1; // ACL connection
2286     event[12] = 0; // encryption disabled
2287     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2288     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2289 }
2290 
2291 void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t * address, uint16_t conn_handle, uint8_t status){
2292     uint8_t event[21];
2293     event[0] = HCI_EVENT_LE_META;
2294     event[1] = sizeof(event) - 2;
2295     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2296     event[3] = status;
2297     bt_store_16(event, 4, conn_handle);
2298     event[6] = 0; // TODO: role
2299     event[7] = address_type;
2300     bt_flip_addr(&event[8], *address);
2301     bt_store_16(event, 14, 0); // interval
2302     bt_store_16(event, 16, 0); // latency
2303     bt_store_16(event, 18, 0); // supervision timeout
2304     event[20] = 0; // master clock accuracy
2305     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2306     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2307 }
2308 
2309 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2310     uint8_t event[6];
2311     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2312     event[1] = sizeof(event) - 2;
2313     event[2] = 0; // status = OK
2314     bt_store_16(event, 3, handle);
2315     event[5] = reason;
2316     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2317     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2318 }
2319 
2320 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2321     if (disable_l2cap_timeouts) return;
2322     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2323     uint8_t event[4];
2324     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2325     event[1] = sizeof(event) - 2;
2326     bt_store_16(event, 2, conn->con_handle);
2327     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2328     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2329 }
2330 
2331 void hci_emit_nr_connections_changed(){
2332     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2333     uint8_t event[3];
2334     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2335     event[1] = sizeof(event) - 2;
2336     event[2] = nr_hci_connections();
2337     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2338     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2339 }
2340 
2341 void hci_emit_hci_open_failed(){
2342     log_info("BTSTACK_EVENT_POWERON_FAILED");
2343     uint8_t event[2];
2344     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2345     event[1] = sizeof(event) - 2;
2346     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2347     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2348 }
2349 
2350 #ifndef EMBEDDED
2351 void hci_emit_btstack_version() {
2352     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2353     uint8_t event[6];
2354     event[0] = BTSTACK_EVENT_VERSION;
2355     event[1] = sizeof(event) - 2;
2356     event[2] = BTSTACK_MAJOR;
2357     event[3] = BTSTACK_MINOR;
2358     bt_store_16(event, 4, BTSTACK_REVISION);
2359     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2360     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2361 }
2362 #endif
2363 
2364 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2365     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2366     uint8_t event[3];
2367     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2368     event[1] = sizeof(event) - 2;
2369     event[2] = enabled;
2370     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2371     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2372 }
2373 
2374 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2375     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2376     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2377     event[1] = sizeof(event) - 2 - 1;
2378     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
2379     bt_flip_addr(&event[3], *addr);
2380     memcpy(&event[9], name, 248);
2381 
2382     event[9+248] = 0;   // assert \0 for log_info
2383     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2384 
2385     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2386     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2387 }
2388 
2389 void hci_emit_discoverable_enabled(uint8_t enabled){
2390     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2391     uint8_t event[3];
2392     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2393     event[1] = sizeof(event) - 2;
2394     event[2] = enabled;
2395     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2396     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2397 }
2398 
2399 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2400     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2401     uint8_t event[5];
2402     int pos = 0;
2403     event[pos++] = GAP_SECURITY_LEVEL;
2404     event[pos++] = sizeof(event) - 2;
2405     bt_store_16(event, 2, con_handle);
2406     pos += 2;
2407     event[pos++] = level;
2408     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2409     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2410 }
2411 
2412 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2413     log_info("hci_emit_dedicated_bonding_result %u ", status);
2414     uint8_t event[9];
2415     int pos = 0;
2416     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2417     event[pos++] = sizeof(event) - 2;
2418     event[pos++] = status;
2419     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2420     pos += 6;
2421     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2422     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2423 }
2424 
2425 // query if remote side supports SSP
2426 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2427     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2428     if (!connection) return 0;
2429     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2430 }
2431 
2432 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2433     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2434 }
2435 
2436 // GAP API
2437 /**
2438  * @bbrief enable/disable bonding. default is enabled
2439  * @praram enabled
2440  */
2441 void gap_set_bondable_mode(int enable){
2442     hci_stack->bondable = enable ? 1 : 0;
2443 }
2444 
2445 /**
2446  * @brief map link keys to security levels
2447  */
2448 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2449     switch (link_key_type){
2450         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2451             return LEVEL_4;
2452         case COMBINATION_KEY:
2453         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2454             return LEVEL_3;
2455         default:
2456             return LEVEL_2;
2457     }
2458 }
2459 
2460 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2461     if (!connection) return LEVEL_0;
2462     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2463     return gap_security_level_for_link_key_type(connection->link_key_type);
2464 }
2465 
2466 
2467 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2468     log_info("gap_mitm_protection_required_for_security_level %u", level);
2469     return level > LEVEL_2;
2470 }
2471 
2472 /**
2473  * @brief get current security level
2474  */
2475 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2476     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2477     if (!connection) return LEVEL_0;
2478     return gap_security_level_for_connection(connection);
2479 }
2480 
2481 /**
2482  * @brief request connection to device to
2483  * @result GAP_AUTHENTICATION_RESULT
2484  */
2485 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2486     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2487     if (!connection){
2488         hci_emit_security_level(con_handle, LEVEL_0);
2489         return;
2490     }
2491     gap_security_level_t current_level = gap_security_level(con_handle);
2492     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2493     if (current_level >= requested_level){
2494         hci_emit_security_level(con_handle, current_level);
2495         return;
2496     }
2497 
2498     connection->requested_security_level = requested_level;
2499 
2500 #if 0
2501     // sending encryption request without a link key results in an error.
2502     // TODO: figure out how to use it properly
2503 
2504     // would enabling ecnryption suffice (>= LEVEL_2)?
2505     if (hci_stack->remote_device_db){
2506         link_key_type_t link_key_type;
2507         link_key_t      link_key;
2508         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2509             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2510                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2511                 return;
2512             }
2513         }
2514     }
2515 #endif
2516 
2517     // try to authenticate connection
2518     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2519     hci_run();
2520 }
2521 
2522 /**
2523  * @brief start dedicated bonding with device. disconnect after bonding
2524  * @param device
2525  * @param request MITM protection
2526  * @result GAP_DEDICATED_BONDING_COMPLETE
2527  */
2528 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2529 
2530     // create connection state machine
2531     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2532 
2533     if (!connection){
2534         return BTSTACK_MEMORY_ALLOC_FAILED;
2535     }
2536 
2537     // delete linkn key
2538     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2539 
2540     // configure LEVEL_2/3, dedicated bonding
2541     connection->state = SEND_CREATE_CONNECTION;
2542     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2543     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2544     connection->bonding_flags = BONDING_DEDICATED;
2545 
2546     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2547 
2548     // handle: connnection failure (connection complete != ok)
2549     // handle: authentication failure
2550     // handle: disconnect on done
2551 
2552     hci_run();
2553 
2554     return 0;
2555 }
2556 
2557 void gap_set_local_name(const char * local_name){
2558     hci_stack->local_name = local_name;
2559 }
2560 
2561 le_command_status_t le_central_start_scan(){
2562     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2563     hci_stack->le_scanning_state = LE_START_SCAN;
2564     hci_run();
2565     return BLE_PERIPHERAL_OK;
2566 }
2567 
2568 le_command_status_t le_central_stop_scan(){
2569     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2570     hci_stack->le_scanning_state = LE_STOP_SCAN;
2571     hci_run();
2572     return BLE_PERIPHERAL_OK;
2573 }
2574 
2575 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2576     hci_stack->le_scan_type     = scan_type;
2577     hci_stack->le_scan_interval = scan_interval;
2578     hci_stack->le_scan_window   = scan_window;
2579     hci_run();
2580 }
2581 
2582 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2583     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2584     if (!conn){
2585         log_info("le_central_connect: no connection exists yet, creating context");
2586         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2587         if (!conn){
2588             // notify client that alloc failed
2589             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
2590             log_info("le_central_connect: failed to alloc hci_connection_t");
2591             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2592         }
2593         conn->state = SEND_CREATE_CONNECTION;
2594         log_info("le_central_connect: send create connection next");
2595         hci_run();
2596         return BLE_PERIPHERAL_OK;
2597     }
2598 
2599     if (!hci_is_le_connection(conn) ||
2600         conn->state == SEND_CREATE_CONNECTION ||
2601         conn->state == SENT_CREATE_CONNECTION) {
2602         hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
2603         log_error("le_central_connect: classic connection or connect is already being created");
2604         return BLE_PERIPHERAL_IN_WRONG_STATE;
2605     }
2606 
2607     log_info("le_central_connect: context exists with state %u", conn->state);
2608     hci_emit_le_connection_complete(conn->address_type, &conn->address, conn->con_handle, 0);
2609     hci_run();
2610     return BLE_PERIPHERAL_OK;
2611 }
2612 
2613 // @assumption: only a single outgoing LE Connection exists
2614 static hci_connection_t * le_central_get_outgoing_connection(){
2615     linked_item_t *it;
2616     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
2617         hci_connection_t * conn = (hci_connection_t *) it;
2618         if (!hci_is_le_connection(conn)) continue;
2619         switch (conn->state){
2620             case SEND_CREATE_CONNECTION:
2621             case SENT_CREATE_CONNECTION:
2622                 return conn;
2623             default:
2624                 break;
2625         };
2626     }
2627     return NULL;
2628 }
2629 
2630 le_command_status_t le_central_connect_cancel(){
2631     hci_connection_t * conn = le_central_get_outgoing_connection();
2632     switch (conn->state){
2633         case SEND_CREATE_CONNECTION:
2634             // skip sending create connection and emit event instead
2635             hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2636             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2637             btstack_memory_hci_connection_free( conn );
2638             break;
2639         case SENT_CREATE_CONNECTION:
2640             // request to send cancel connection
2641             conn->state = SEND_CANCEL_CONNECTION;
2642             hci_run();
2643             break;
2644         default:
2645             break;
2646     }
2647     return BLE_PERIPHERAL_OK;
2648 }
2649 
2650 /**
2651  * @brief Updates the connection parameters for a given LE connection
2652  * @param handle
2653  * @param conn_interval_min (unit: 1.25ms)
2654  * @param conn_interval_max (unit: 1.25ms)
2655  * @param conn_latency
2656  * @param supervision_timeout (unit: 10ms)
2657  * @returns 0 if ok
2658  */
2659 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2660     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2661     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2662     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2663     connection->le_conn_interval_min = conn_interval_min;
2664     connection->le_conn_interval_max = conn_interval_max;
2665     connection->le_conn_latency = conn_latency;
2666     connection->le_supervision_timeout = supervision_timeout;
2667     return 0;
2668 }
2669 
2670 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2671     hci_connection_t * conn = hci_connection_for_handle(handle);
2672     if (!conn){
2673         hci_emit_disconnection_complete(handle, 0);
2674         return BLE_PERIPHERAL_OK;
2675     }
2676     conn->state = SEND_DISCONNECT;
2677     hci_run();
2678     return BLE_PERIPHERAL_OK;
2679 }
2680 
2681 void hci_disconnect_all(){
2682     linked_list_iterator_t it;
2683     linked_list_iterator_init(&it, &hci_stack->connections);
2684     while (linked_list_iterator_has_next(&it)){
2685         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
2686         if (con->state == SENT_DISCONNECT) continue;
2687         con->state = SEND_DISCONNECT;
2688     }
2689     hci_run();
2690 }
2691