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