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