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