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