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