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