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