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