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