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