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