xref: /btstack/src/hci.c (revision 36af3e18b695b8180fdc9a1757a97769b6cc8e76)
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 #ifdef HAVE_BLE
517 static void le_handle_advertisement_report(uint8_t *packet, int size){
518     int num_reports = packet[3];
519     int i;
520     int total_data_length = 0;
521     int data_offset = 0;
522 
523     for (i=0; i<num_reports;i++){
524         total_data_length += packet[4+num_reports*8+i];
525     }
526 
527     for (i=0; i<num_reports;i++){
528         int pos = 0;
529         uint8_t data_length = packet[4+num_reports*8+i];
530         uint8_t event_size = 10 + data_length;
531         uint8_t event[2 + event_size ];
532         event[pos++] = GAP_LE_ADVERTISING_REPORT;
533         event[pos++] = event_size;
534         event[pos++] = packet[4+i]; // event_type;
535         event[pos++] = packet[4+num_reports+i]; // address_type;
536         memcpy(&event[pos], &packet[4+num_reports*2+i*6], 6); // bt address
537         pos += 6;
538         event[pos++] = packet[4+num_reports*9+total_data_length + i];
539         event[pos++] = data_length;
540         memcpy(&packet[4+num_reports*9+data_offset], &event[pos], data_length);
541         data_offset += data_length;
542         pos += data_length;
543         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
544     }
545 }
546 #endif
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 #ifdef HAVE_BLE
1364     // handle le scan
1365     if (hci_stack->state == HCI_STATE_WORKING){
1366         switch(hci_stack->le_scanning_state){
1367             case LE_START_SCAN:
1368                 hci_stack->le_scanning_state = LE_SCANNING;
1369                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1370                 return;
1371 
1372             case LE_STOP_SCAN:
1373                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1374                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1375                 return;
1376             default:
1377                 break;
1378         }
1379     }
1380 #endif
1381 
1382     // send pending HCI commands
1383     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1384         connection = (hci_connection_t *) it;
1385 
1386         if (connection->state == SEND_DISCONNECT){
1387             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1388             connection->state = SENT_DISCONNECT;
1389             return;
1390         }
1391 
1392         if (connection->state == SEND_CREATE_CONNECTION){
1393             switch(connection->address_type){
1394                 case BD_ADDR_TYPE_CLASSIC:
1395                     log_info("sending hci_create_connection\n");
1396                     hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1397                     break;
1398                 default:
1399 #ifdef HAVE_BLE
1400                     log_info("sending hci_le_create_connection\n");
1401                     hci_send_cmd(&hci_le_create_connection,
1402                                  1000,      // scan interval: 625 ms
1403                                  1000,      // scan interval: 625 ms
1404                                  0,         // don't use whitelist
1405                                  connection->address_type, // peer address type
1406                                  connection->address,       // peer bd addr
1407                                  0,         // our addr type: public
1408                                  80,        // conn interval min
1409                                  80,        // conn interval max (3200 * 0.625)
1410                                  0,         // conn latency
1411                                  2000,      // supervision timeout
1412                                  0,         // min ce length
1413                                  1000       // max ce length
1414                                  );
1415 
1416                     connection->state = SENT_CREATE_CONNECTION;
1417 #endif
1418                     break;
1419             }
1420             return;
1421         }
1422 
1423         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1424             log_info("sending hci_accept_connection_request\n");
1425             connection->state = ACCEPTED_CONNECTION_REQUEST;
1426             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1427             return;
1428         }
1429 
1430         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1431             log_info("responding to link key request\n");
1432             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1433             link_key_t link_key;
1434             link_key_type_t link_key_type;
1435             if ( hci_stack->remote_device_db
1436               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1437               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1438                connection->link_key_type = link_key_type;
1439                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1440             } else {
1441                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1442             }
1443             return;
1444         }
1445 
1446         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1447             log_info("denying to pin request\n");
1448             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1449             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1450             return;
1451         }
1452 
1453         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1454             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1455             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1456             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1457                 // tweak authentication requirements
1458                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1459                 if (connection->bonding_flags & BONDING_DEDICATED){
1460                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1461                 }
1462                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1463                     authreq |= 1;
1464                 }
1465                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1466             } else {
1467                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1468             }
1469             return;
1470         }
1471 
1472         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1473             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1474             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1475             return;
1476         }
1477 
1478         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1479             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1480             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1481             return;
1482         }
1483 
1484         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1485             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1486             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1487             return;
1488         }
1489 
1490         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1491             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1492             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1493             return;
1494         }
1495         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1496             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1497             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1498             return;
1499         }
1500         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1501             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1502             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1503             return;
1504         }
1505         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1506             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1507             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1508             return;
1509         }
1510     }
1511 
1512     switch (hci_stack->state){
1513         case HCI_STATE_INITIALIZING:
1514             // log_info("hci_init: substate %u\n", hci_stack->substate);
1515             if (hci_stack->substate % 2) {
1516                 // odd: waiting for command completion
1517                 return;
1518             }
1519             switch (hci_stack->substate >> 1){
1520                 case 0: // RESET
1521                     hci_send_cmd(&hci_reset);
1522 
1523                     if (hci_stack->config == 0 || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
1524                         // skip baud change
1525                         hci_stack->substate = 4; // >> 1 = 2
1526                     }
1527                     break;
1528                 case 1: // SEND BAUD CHANGE
1529                     hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
1530                     hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1531                     break;
1532                 case 2: // LOCAL BAUD CHANGE
1533                     hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
1534                     hci_stack->substate += 2;
1535                     // break missing here for fall through
1536 
1537                 case 3:
1538                     // Custom initialization
1539                     if (hci_stack->control && hci_stack->control->next_cmd){
1540                         int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
1541                         if (valid_cmd){
1542                             int size = 3 + hci_stack->hci_packet_buffer[2];
1543                             hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1544                             hci_stack->substate = 4; // more init commands
1545                             break;
1546                         }
1547                         log_info("hci_run: init script done\n\r");
1548                     }
1549                     // otherwise continue
1550 					hci_send_cmd(&hci_read_bd_addr);
1551 					break;
1552 				case 4:
1553 					hci_send_cmd(&hci_read_buffer_size);
1554 					break;
1555                 case 5:
1556                     hci_send_cmd(&hci_read_local_supported_features);
1557                     break;
1558                 case 6:
1559                     if (hci_le_supported()){
1560                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1561                     } else {
1562                         // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1563                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1564                     }
1565 
1566                     // skip Classic init commands for LE only chipsets
1567                     if (!hci_classic_supported()){
1568                         if (hci_le_supported()){
1569                             hci_stack->substate = 11 << 1;    // skip all classic command
1570                         } else {
1571                             log_error("Neither BR/EDR nor LE supported");
1572                             hci_stack->substate = 13 << 1;    // skip all
1573                         }
1574                     }
1575                     break;
1576                 case 7:
1577                     if (hci_ssp_supported()){
1578                         hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1579                         break;
1580                     }
1581                     hci_stack->substate += 2;
1582                     // break missing here for fall through
1583 
1584                 case 8:
1585                     // ca. 15 sec
1586                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1587                     break;
1588                 case 9:
1589                     hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1590                     break;
1591                 case 10:
1592                     if (hci_stack->local_name){
1593                         hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
1594                     } else {
1595                         char hostname[30];
1596 #ifdef EMBEDDED
1597                         // BTstack-11:22:33:44:55:66
1598                         strcpy(hostname, "BTstack ");
1599                         strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
1600                         printf("---> Name %s\n", hostname);
1601 #else
1602                         // hostname for POSIX systems
1603                         gethostname(hostname, 30);
1604                         hostname[29] = '\0';
1605 #endif
1606                         hci_send_cmd(&hci_write_local_name, hostname);
1607                     }
1608                     break;
1609                 case 11:
1610 					hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1611                     if (!hci_le_supported()){
1612                         // SKIP LE init for Classic only configuration
1613                         hci_stack->substate = 13 << 1;
1614                     }
1615 					break;
1616 
1617 #ifdef HAVE_BLE
1618                 // LE INIT
1619                 case 12:
1620                     hci_send_cmd(&hci_le_read_buffer_size);
1621                     break;
1622                 case 13:
1623                     // LE Supported Host = 1, Simultaneous Host = 0
1624                     hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1625                     break;
1626 #endif
1627 
1628                 // DONE
1629                 case 14:
1630                     // done.
1631                     hci_stack->state = HCI_STATE_WORKING;
1632                     hci_emit_state();
1633                     break;
1634                 default:
1635                     break;
1636             }
1637             hci_stack->substate++;
1638             break;
1639 
1640         case HCI_STATE_HALTING:
1641 
1642             log_info("HCI_STATE_HALTING\n");
1643             // close all open connections
1644             connection =  (hci_connection_t *) hci_stack->connections;
1645             if (connection){
1646 
1647                 // send disconnect
1648                 if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return;
1649 
1650                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1651                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1652 
1653                 // send disconnected event right away - causes higher layer connections to get closed, too.
1654                 hci_shutdown_connection(connection);
1655                 return;
1656             }
1657             log_info("HCI_STATE_HALTING, calling off\n");
1658 
1659             // switch mode
1660             hci_power_control_off();
1661 
1662             log_info("HCI_STATE_HALTING, emitting state\n");
1663             hci_emit_state();
1664             log_info("HCI_STATE_HALTING, done\n");
1665             break;
1666 
1667         case HCI_STATE_FALLING_ASLEEP:
1668             switch(hci_stack->substate) {
1669                 case 0:
1670                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1671                     // close all open connections
1672                     connection =  (hci_connection_t *) hci_stack->connections;
1673 
1674 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1675                     // don't close connections, if H4 supports power management
1676                     if (bt_control_iphone_power_management_enabled()){
1677                         connection = NULL;
1678                     }
1679 #endif
1680                     if (connection){
1681 
1682                         // send disconnect
1683                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1684 
1685                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1686                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1687 
1688                         // send disconnected event right away - causes higher layer connections to get closed, too.
1689                         hci_shutdown_connection(connection);
1690                         return;
1691                     }
1692 
1693                     if (hci_classic_supported()){
1694                         // disable page and inquiry scan
1695                         if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return;
1696 
1697                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
1698                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
1699 
1700                         // continue in next sub state
1701                         hci_stack->substate++;
1702                         break;
1703                     }
1704                     // fall through for ble-only chips
1705 
1706                 case 2:
1707                     log_info("HCI_STATE_HALTING, calling sleep\n");
1708 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1709                     // don't actually go to sleep, if H4 supports power management
1710                     if (bt_control_iphone_power_management_enabled()){
1711                         // SLEEP MODE reached
1712                         hci_stack->state = HCI_STATE_SLEEPING;
1713                         hci_emit_state();
1714                         break;
1715                     }
1716 #endif
1717                     // switch mode
1718                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
1719                     hci_emit_state();
1720                     break;
1721 
1722                 default:
1723                     break;
1724             }
1725             break;
1726 
1727         default:
1728             break;
1729     }
1730 }
1731 
1732 int hci_send_cmd_packet(uint8_t *packet, int size){
1733     bd_addr_t addr;
1734     hci_connection_t * conn;
1735     // house-keeping
1736 
1737     // create_connection?
1738     if (IS_COMMAND(packet, hci_create_connection)){
1739         bt_flip_addr(addr, &packet[3]);
1740         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1741 
1742         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1743         if (!conn){
1744             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1745             if (!conn){
1746                 // notify client that alloc failed
1747                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1748                 return 0; // don't sent packet to controller
1749             }
1750             conn->state = SEND_CREATE_CONNECTION;
1751         }
1752         log_info("conn state %u", conn->state);
1753         switch (conn->state){
1754             // if connection active exists
1755             case OPEN:
1756                 // and OPEN, emit connection complete command, don't send to controller
1757                 hci_emit_connection_complete(conn, 0);
1758                 return 0;
1759             case SEND_CREATE_CONNECTION:
1760                 // connection created by hci, e.g. dedicated bonding
1761                 break;
1762             default:
1763                 // otherwise, just ignore as it is already in the open process
1764                 return 0;
1765         }
1766         conn->state = SENT_CREATE_CONNECTION;
1767     }
1768 
1769     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1770         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1771     }
1772     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1773         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1774     }
1775 
1776     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1777         if (hci_stack->remote_device_db){
1778             bt_flip_addr(addr, &packet[3]);
1779             hci_stack->remote_device_db->delete_link_key(&addr);
1780         }
1781     }
1782 
1783     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
1784     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
1785         bt_flip_addr(addr, &packet[3]);
1786         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1787         if (conn){
1788             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
1789         }
1790     }
1791 
1792     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
1793     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
1794     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
1795     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
1796         bt_flip_addr(addr, &packet[3]);
1797         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1798         if (conn){
1799             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
1800         }
1801     }
1802 
1803 #ifdef HAVE_BLE
1804     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
1805         hci_stack->adv_addr_type = packet[8];
1806     }
1807     if (IS_COMMAND(packet, hci_le_set_random_address)){
1808         bt_flip_addr(hci_stack->adv_address, &packet[3]);
1809     }
1810 #endif
1811 
1812     hci_stack->num_cmd_packets--;
1813     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1814 
1815     // free packet buffer for synchronous transport implementations
1816     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
1817         hci_stack->hci_packet_buffer_reserved = 0;
1818     }
1819 
1820     return err;
1821 }
1822 
1823 // disconnect because of security block
1824 void hci_disconnect_security_block(hci_con_handle_t con_handle){
1825     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1826     if (!connection) return;
1827     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
1828 }
1829 
1830 
1831 // Configure Secure Simple Pairing
1832 
1833 // enable will enable SSP during init
1834 void hci_ssp_set_enable(int enable){
1835     hci_stack->ssp_enable = enable;
1836 }
1837 
1838 int hci_local_ssp_activated(){
1839     return hci_ssp_supported() && hci_stack->ssp_enable;
1840 }
1841 
1842 // if set, BTstack will respond to io capability request using authentication requirement
1843 void hci_ssp_set_io_capability(int io_capability){
1844     hci_stack->ssp_io_capability = io_capability;
1845 }
1846 void hci_ssp_set_authentication_requirement(int authentication_requirement){
1847     hci_stack->ssp_authentication_requirement = authentication_requirement;
1848 }
1849 
1850 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1851 void hci_ssp_set_auto_accept(int auto_accept){
1852     hci_stack->ssp_auto_accept = auto_accept;
1853 }
1854 
1855 /**
1856  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1857  */
1858 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1859     va_list argptr;
1860     va_start(argptr, cmd);
1861     uint16_t size = hci_create_cmd_internal(hci_stack->hci_packet_buffer, cmd, argptr);
1862     va_end(argptr);
1863     return hci_send_cmd_packet(hci_stack->hci_packet_buffer, size);
1864 }
1865 
1866 // Create various non-HCI events.
1867 // TODO: generalize, use table similar to hci_create_command
1868 
1869 void hci_emit_state(){
1870     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
1871     uint8_t event[3];
1872     event[0] = BTSTACK_EVENT_STATE;
1873     event[1] = sizeof(event) - 2;
1874     event[2] = hci_stack->state;
1875     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1876     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1877 }
1878 
1879 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1880     uint8_t event[13];
1881     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1882     event[1] = sizeof(event) - 2;
1883     event[2] = status;
1884     bt_store_16(event, 3, conn->con_handle);
1885     bt_flip_addr(&event[5], conn->address);
1886     event[11] = 1; // ACL connection
1887     event[12] = 0; // encryption disabled
1888     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1889     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1890 }
1891 
1892 void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){
1893     uint8_t event[21];
1894     event[0] = HCI_EVENT_LE_META;
1895     event[1] = sizeof(event) - 2;
1896     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
1897     event[3] = status;
1898     bt_store_16(event, 4, conn->con_handle);
1899     event[6] = 0; // TODO: role
1900     event[7] = conn->address_type;
1901     bt_flip_addr(&event[8], conn->address);
1902     bt_store_16(event, 14, 0); // interval
1903     bt_store_16(event, 16, 0); // latency
1904     bt_store_16(event, 18, 0); // supervision timeout
1905     event[20] = 0; // master clock accuracy
1906     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1907     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1908 }
1909 
1910 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1911     uint8_t event[6];
1912     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1913     event[1] = sizeof(event) - 2;
1914     event[2] = 0; // status = OK
1915     bt_store_16(event, 3, handle);
1916     event[5] = reason;
1917     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1918     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1919 }
1920 
1921 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1922     if (disable_l2cap_timeouts) return;
1923     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1924     uint8_t event[4];
1925     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1926     event[1] = sizeof(event) - 2;
1927     bt_store_16(event, 2, conn->con_handle);
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_nr_connections_changed(){
1933     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1934     uint8_t event[3];
1935     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1936     event[1] = sizeof(event) - 2;
1937     event[2] = nr_hci_connections();
1938     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1939     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1940 }
1941 
1942 void hci_emit_hci_open_failed(){
1943     log_info("BTSTACK_EVENT_POWERON_FAILED");
1944     uint8_t event[2];
1945     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1946     event[1] = sizeof(event) - 2;
1947     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1948     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1949 }
1950 
1951 #ifndef EMBEDDED
1952 void hci_emit_btstack_version() {
1953     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1954     uint8_t event[6];
1955     event[0] = BTSTACK_EVENT_VERSION;
1956     event[1] = sizeof(event) - 2;
1957     event[2] = BTSTACK_MAJOR;
1958     event[3] = BTSTACK_MINOR;
1959     bt_store_16(event, 4, BTSTACK_REVISION);
1960     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1961     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1962 }
1963 #endif
1964 
1965 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1966     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1967     uint8_t event[3];
1968     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1969     event[1] = sizeof(event) - 2;
1970     event[2] = enabled;
1971     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1972     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1973 }
1974 
1975 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1976     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1977     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1978     event[1] = sizeof(event) - 2 - 1;
1979     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1980     bt_flip_addr(&event[3], *addr);
1981     memcpy(&event[9], name, 248);
1982 
1983     event[9+248] = 0;   // assert \0 for log_info
1984     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
1985 
1986     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
1987     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
1988 }
1989 
1990 void hci_emit_discoverable_enabled(uint8_t enabled){
1991     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
1992     uint8_t event[3];
1993     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1994     event[1] = sizeof(event) - 2;
1995     event[2] = enabled;
1996     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1997     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1998 }
1999 
2000 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2001     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2002     uint8_t event[5];
2003     int pos = 0;
2004     event[pos++] = GAP_SECURITY_LEVEL;
2005     event[pos++] = sizeof(event) - 2;
2006     bt_store_16(event, 2, con_handle);
2007     pos += 2;
2008     event[pos++] = level;
2009     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2010     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2011 }
2012 
2013 void hci_emit_dedicated_bonding_result(hci_connection_t * connection, uint8_t status){
2014     log_info("hci_emit_dedicated_bonding_result %u ", status);
2015     uint8_t event[9];
2016     int pos = 0;
2017     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2018     event[pos++] = sizeof(event) - 2;
2019     event[pos++] = status;
2020     bt_flip_addr( * (bd_addr_t *) &event[pos], connection->address);
2021     pos += 6;
2022     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2023     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2024 }
2025 
2026 // query if remote side supports SSP
2027 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2028     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2029     if (!connection) return 0;
2030     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2031 }
2032 
2033 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2034     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2035 }
2036 
2037 // GAP API
2038 /**
2039  * @bbrief enable/disable bonding. default is enabled
2040  * @praram enabled
2041  */
2042 void gap_set_bondable_mode(int enable){
2043     hci_stack->bondable = enable ? 1 : 0;
2044 }
2045 
2046 /**
2047  * @brief map link keys to security levels
2048  */
2049 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2050     switch (link_key_type){
2051         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2052             return LEVEL_4;
2053         case COMBINATION_KEY:
2054         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2055             return LEVEL_3;
2056         default:
2057             return LEVEL_2;
2058     }
2059 }
2060 
2061 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2062     if (!connection) return LEVEL_0;
2063     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2064     return gap_security_level_for_link_key_type(connection->link_key_type);
2065 }
2066 
2067 
2068 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2069     printf("gap_mitm_protection_required_for_security_level %u\n", level);
2070     return level > LEVEL_2;
2071 }
2072 
2073 /**
2074  * @brief get current security level
2075  */
2076 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2077     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2078     if (!connection) return LEVEL_0;
2079     return gap_security_level_for_connection(connection);
2080 }
2081 
2082 /**
2083  * @brief request connection to device to
2084  * @result GAP_AUTHENTICATION_RESULT
2085  */
2086 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2087     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2088     if (!connection){
2089         hci_emit_security_level(con_handle, LEVEL_0);
2090         return;
2091     }
2092     gap_security_level_t current_level = gap_security_level(con_handle);
2093     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2094     if (current_level >= requested_level){
2095         hci_emit_security_level(con_handle, current_level);
2096         return;
2097     }
2098 
2099     connection->requested_security_level = requested_level;
2100 
2101     // would enabling ecnryption suffice (>= LEVEL_2)?
2102     if (hci_stack->remote_device_db){
2103         link_key_type_t link_key_type;
2104         link_key_t      link_key;
2105         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2106             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2107                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2108                 return;
2109             }
2110         }
2111     }
2112 
2113     // try to authenticate connection
2114     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2115     hci_run();
2116 }
2117 
2118 /**
2119  * @brief start dedicated bonding with device. disconnect after bonding
2120  * @param device
2121  * @param request MITM protection
2122  * @result GAP_DEDICATED_BONDING_COMPLETE
2123  */
2124 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2125 
2126     // create connection state machine
2127     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2128 
2129     if (!connection){
2130         return BTSTACK_MEMORY_ALLOC_FAILED;
2131     }
2132 
2133     // delete linkn key
2134     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2135 
2136     // configure LEVEL_2/3, dedicated bonding
2137     connection->state = SEND_CREATE_CONNECTION;
2138     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2139     printf("gap_dedicated_bonding, mitm %u -> level %u\n", mitm_protection_required, connection->requested_security_level);
2140     connection->bonding_flags = BONDING_DEDICATED;
2141 
2142     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2143 
2144     // handle: connnection failure (connection complete != ok)
2145     // handle: authentication failure
2146     // handle: disconnect on done
2147 
2148     hci_run();
2149 
2150     return 0;
2151 }
2152 
2153 void gap_set_local_name(const char * local_name){
2154     hci_stack->local_name = local_name;
2155 }
2156 
2157 le_command_status_t le_central_start_scan(){
2158     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2159     hci_stack->le_scanning_state = LE_START_SCAN;
2160     hci_run();
2161     return BLE_PERIPHERAL_OK;
2162 }
2163 
2164 le_command_status_t le_central_stop_scan(){
2165     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2166     hci_stack->le_scanning_state = LE_STOP_SCAN;
2167     hci_run();
2168     return BLE_PERIPHERAL_OK;
2169 }
2170 
2171 
2172 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2173     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2174     log_info("le_central_connect, conn struct %p", conn);
2175     if (!conn){
2176         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2177         if (!conn){
2178             // notify client that alloc failed
2179             hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2180             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2181         }
2182         conn->state = SEND_CREATE_CONNECTION;
2183         log_info("le_central_connect, state %u", conn->state);
2184         hci_run();
2185         return BLE_PERIPHERAL_OK;
2186     }
2187     log_info("le_central_connect, state %u", conn->state);
2188     hci_emit_le_connection_complete(conn, 0);
2189     hci_run();
2190     return BLE_PERIPHERAL_OK;
2191 }
2192 
2193 
2194 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2195     hci_connection_t * conn = hci_connection_for_handle(handle);
2196     if (!conn){
2197         hci_emit_le_connection_complete(conn, 0);
2198         return BLE_PERIPHERAL_OK;
2199     }
2200     conn->state = SEND_DISCONNECT;
2201     hci_run();
2202     return BLE_PERIPHERAL_OK;
2203 }
2204