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