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