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