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