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