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