xref: /btstack/src/hci.c (revision 6724cd9e0e8ff005aa86cb62959276bf44acdda8)
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                     // connection failed, remove entry
615                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
616                     btstack_memory_hci_connection_free( conn );
617 
618                     // if authentication error, also delete link key
619                     if (packet[2] == 0x05) {
620                         hci_drop_link_key_for_bd_addr(&addr);
621                     }
622                 }
623             }
624             break;
625 
626         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
627             handle = READ_BT_16(packet, 3);
628             conn = hci_connection_for_handle(handle);
629             if (!conn) break;
630             if (!packet[2]){
631                 uint8_t * features = &packet[5];
632                 if (features[6] & (1 << 3)){
633                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
634                 }
635             }
636             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
637             break;
638 
639         case HCI_EVENT_LINK_KEY_REQUEST:
640             log_info("HCI_EVENT_LINK_KEY_REQUEST\n");
641             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
642             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
643             if (hci_stack.bondable && !hci_stack.remote_device_db) break;
644             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
645             hci_run();
646             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
647             return;
648 
649         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
650             bt_flip_addr(addr, &packet[2]);
651             conn = connection_for_address(addr);
652             if (!conn) break;
653             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
654             link_key_type_t link_key_type = packet[24];
655             // Change Connection Encryption keeps link key type
656             if (link_key_type != CHANGED_COMBINATION_KEY){
657                 conn->link_key_type = link_key_type;
658             }
659             if (!hci_stack.remote_device_db) break;
660             hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
661             // still forward event to allow dismiss of pairing dialog
662             break;
663         }
664 
665         case HCI_EVENT_PIN_CODE_REQUEST:
666             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
667             // non-bondable mode: pin code negative reply will be sent
668             if (!hci_stack.bondable){
669                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
670                 hci_run();
671                 return;
672             }
673             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
674             if (!hci_stack.remote_device_db) break;
675             bt_flip_addr(addr, &packet[2]);
676             hci_stack.remote_device_db->delete_link_key(&addr);
677             break;
678 
679         case HCI_EVENT_IO_CAPABILITY_REQUEST:
680             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
681             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
682             break;
683 
684         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
685             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
686             if (!hci_stack.ssp_auto_accept) break;
687             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
688             break;
689 
690         case HCI_EVENT_USER_PASSKEY_REQUEST:
691             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
692             if (!hci_stack.ssp_auto_accept) break;
693             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
694             break;
695 
696         case HCI_EVENT_ENCRYPTION_CHANGE:
697             if (packet[2]) break;   // error status
698             handle = READ_BT_16(packet, 3);
699             conn = hci_connection_for_handle(handle);
700             if (!conn) break;
701             if (packet[5]){
702                 conn->authentication_flags |= CONNECTION_ENCRYPTED;
703             } else {
704                 conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
705             }
706             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
707             break;
708 
709         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
710             handle = READ_BT_16(packet, 3);
711             conn = hci_connection_for_handle(handle);
712             if (!conn) break;
713             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
714                 // link key sufficient for requested security
715                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
716             } else {
717                 // not enough
718                hci_emit_security_level(handle, gap_security_level_for_connection(conn));
719             }
720             break;
721 
722 #ifndef EMBEDDED
723         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
724             if (!hci_stack.remote_device_db) break;
725             if (packet[2]) break; // status not ok
726             bt_flip_addr(addr, &packet[3]);
727             // fix for invalid remote names - terminate on 0xff
728             for (i=0; i<248;i++){
729                 if (packet[9+i] == 0xff){
730                     packet[9+i] = 0;
731                     break;
732                 }
733             }
734             memset(&device_name, 0, sizeof(device_name_t));
735             strncpy((char*) device_name, (char*) &packet[9], 248);
736             hci_stack.remote_device_db->put_name(&addr, &device_name);
737             break;
738 
739         case HCI_EVENT_INQUIRY_RESULT:
740         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
741             if (!hci_stack.remote_device_db) break;
742             // first send inq result packet
743             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
744             // then send cached remote names
745             for (i=0; i<packet[2];i++){
746                 bt_flip_addr(addr, &packet[3+i*6]);
747                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
748                     hci_emit_remote_name_cached(&addr, &device_name);
749                 }
750             }
751             return;
752 #endif
753 
754         case HCI_EVENT_DISCONNECTION_COMPLETE:
755             if (!packet[2]){
756                 handle = READ_BT_16(packet, 3);
757                 hci_connection_t * conn = hci_connection_for_handle(handle);
758                 if (conn) {
759                     hci_shutdown_connection(conn);
760                 }
761             }
762             break;
763 
764         case HCI_EVENT_HARDWARE_ERROR:
765             if(hci_stack.control && hci_stack.control->hw_error){
766                 (*hci_stack.control->hw_error)();
767             }
768             break;
769 
770 #ifdef HAVE_BLE
771         case HCI_EVENT_LE_META:
772             switch (packet[2]) {
773                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
774                     // Connection management
775                     bt_flip_addr(addr, &packet[8]);
776                     log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr));
777                     // LE connections are auto-accepted, so just create a connection if there isn't one already
778                     conn = connection_for_address(addr);
779                     if (packet[3]){
780                         if (conn){
781                             // outgoing connection failed, remove entry
782                             linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
783                             btstack_memory_hci_connection_free( conn );
784 
785                         }
786                         // if authentication error, also delete link key
787                         if (packet[3] == 0x05) {
788                             hci_drop_link_key_for_bd_addr(&addr);
789                         }
790                         break;
791                     }
792                     if (!conn){
793                         conn = create_connection_for_addr(addr);
794                     }
795                     if (!conn){
796                         // no memory
797                         break;
798                     }
799 
800                     conn->state = OPEN;
801                     conn->con_handle = READ_BT_16(packet, 4);
802 
803                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
804 
805                     // restart timer
806                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
807                     // run_loop_add_timer(&conn->timeout);
808 
809                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
810 
811                     hci_emit_nr_connections_changed();
812                     break;
813 
814             // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]);
815 
816                 default:
817                     break;
818             }
819             break;
820 #endif
821 
822         default:
823             break;
824     }
825 
826     // handle BT initialization
827     if (hci_stack.state == HCI_STATE_INITIALIZING){
828         if (hci_stack.substate % 2){
829             // odd: waiting for event
830             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
831                 // wait for explicit COMMAND COMPLETE on RESET
832                 if (hci_stack.substate > 1 || COMMAND_COMPLETE_EVENT(packet, hci_reset)) {
833                     hci_stack.substate++;
834                 }
835             }
836         }
837     }
838 
839     // help with BT sleep
840     if (hci_stack.state == HCI_STATE_FALLING_ASLEEP
841         && hci_stack.substate == 1
842         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
843         hci_stack.substate++;
844     }
845 
846     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
847 
848 	// execute main loop
849 	hci_run();
850 }
851 
852 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
853     switch (packet_type) {
854         case HCI_EVENT_PACKET:
855             event_handler(packet, size);
856             break;
857         case HCI_ACL_DATA_PACKET:
858             acl_handler(packet, size);
859             break;
860         default:
861             break;
862     }
863 }
864 
865 /** Register HCI packet handlers */
866 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
867     hci_stack.packet_handler = handler;
868 }
869 
870 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
871 
872     // reference to use transport layer implementation
873     hci_stack.hci_transport = transport;
874 
875     // references to used control implementation
876     hci_stack.control = control;
877 
878     // reference to used config
879     hci_stack.config = config;
880 
881     // no connections yet
882     hci_stack.connections = NULL;
883     hci_stack.discoverable = 0;
884     hci_stack.connectable = 0;
885     hci_stack.bondable = 1;
886 
887     // no pending cmds
888     hci_stack.decline_reason = 0;
889     hci_stack.new_scan_enable_value = 0xff;
890 
891     // higher level handler
892     hci_stack.packet_handler = dummy_handler;
893 
894     // store and open remote device db
895     hci_stack.remote_device_db = remote_device_db;
896     if (hci_stack.remote_device_db) {
897         hci_stack.remote_device_db->open();
898     }
899 
900     // max acl payload size defined in config.h
901     hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
902 
903     // register packet handlers with transport
904     transport->register_packet_handler(&packet_handler);
905 
906     hci_stack.state = HCI_STATE_OFF;
907 
908     // class of device
909     hci_stack.class_of_device = 0x007a020c; // Smartphone
910 
911     // Secure Simple Pairing default: enable, no I/O capabilities, auto accept
912     hci_stack.ssp_enable = 1;
913     hci_stack.ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
914     hci_stack.ssp_authentication_requirement = 0;
915     hci_stack.ssp_auto_accept = 1;
916 
917     // LE
918     hci_stack.adv_addr_type = 0;
919     memset(hci_stack.adv_address, 0, 6);
920 }
921 
922 void hci_close(){
923     // close remote device db
924     if (hci_stack.remote_device_db) {
925         hci_stack.remote_device_db->close();
926     }
927     while (hci_stack.connections) {
928         hci_shutdown_connection((hci_connection_t *) hci_stack.connections);
929 }
930     hci_power_control(HCI_POWER_OFF);
931 }
932 
933 // State-Module-Driver overview
934 // state                    module  low-level
935 // HCI_STATE_OFF             off      close
936 // HCI_STATE_INITIALIZING,   on       open
937 // HCI_STATE_WORKING,        on       open
938 // HCI_STATE_HALTING,        on       open
939 // HCI_STATE_SLEEPING,    off/sleep   close
940 // HCI_STATE_FALLING_ASLEEP  on       open
941 
942 static int hci_power_control_on(void){
943 
944     // power on
945     int err = 0;
946     if (hci_stack.control && hci_stack.control->on){
947         err = (*hci_stack.control->on)(hci_stack.config);
948     }
949     if (err){
950         log_error( "POWER_ON failed\n");
951         hci_emit_hci_open_failed();
952         return err;
953     }
954 
955     // open low-level device
956     err = hci_stack.hci_transport->open(hci_stack.config);
957     if (err){
958         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
959         if (hci_stack.control && hci_stack.control->off){
960             (*hci_stack.control->off)(hci_stack.config);
961         }
962         hci_emit_hci_open_failed();
963         return err;
964     }
965     return 0;
966 }
967 
968 static void hci_power_control_off(void){
969 
970     log_info("hci_power_control_off\n");
971 
972     // close low-level device
973     hci_stack.hci_transport->close(hci_stack.config);
974 
975     log_info("hci_power_control_off - hci_transport closed\n");
976 
977     // power off
978     if (hci_stack.control && hci_stack.control->off){
979         (*hci_stack.control->off)(hci_stack.config);
980     }
981 
982     log_info("hci_power_control_off - control closed\n");
983 
984     hci_stack.state = HCI_STATE_OFF;
985 }
986 
987 static void hci_power_control_sleep(void){
988 
989     log_info("hci_power_control_sleep\n");
990 
991 #if 0
992     // don't close serial port during sleep
993 
994     // close low-level device
995     hci_stack.hci_transport->close(hci_stack.config);
996 #endif
997 
998     // sleep mode
999     if (hci_stack.control && hci_stack.control->sleep){
1000         (*hci_stack.control->sleep)(hci_stack.config);
1001     }
1002 
1003     hci_stack.state = HCI_STATE_SLEEPING;
1004 }
1005 
1006 static int hci_power_control_wake(void){
1007 
1008     log_info("hci_power_control_wake\n");
1009 
1010     // wake on
1011     if (hci_stack.control && hci_stack.control->wake){
1012         (*hci_stack.control->wake)(hci_stack.config);
1013     }
1014 
1015 #if 0
1016     // open low-level device
1017     int err = hci_stack.hci_transport->open(hci_stack.config);
1018     if (err){
1019         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
1020         if (hci_stack.control && hci_stack.control->off){
1021             (*hci_stack.control->off)(hci_stack.config);
1022         }
1023         hci_emit_hci_open_failed();
1024         return err;
1025     }
1026 #endif
1027 
1028     return 0;
1029 }
1030 
1031 
1032 int hci_power_control(HCI_POWER_MODE power_mode){
1033 
1034     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
1035 
1036     int err = 0;
1037     switch (hci_stack.state){
1038 
1039         case HCI_STATE_OFF:
1040             switch (power_mode){
1041                 case HCI_POWER_ON:
1042                     err = hci_power_control_on();
1043                     if (err) return err;
1044                     // set up state machine
1045                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1046                     hci_stack.state = HCI_STATE_INITIALIZING;
1047                     hci_stack.substate = 0;
1048                     break;
1049                 case HCI_POWER_OFF:
1050                     // do nothing
1051                     break;
1052                 case HCI_POWER_SLEEP:
1053                     // do nothing (with SLEEP == OFF)
1054                     break;
1055             }
1056             break;
1057 
1058         case HCI_STATE_INITIALIZING:
1059             switch (power_mode){
1060                 case HCI_POWER_ON:
1061                     // do nothing
1062                     break;
1063                 case HCI_POWER_OFF:
1064                     // no connections yet, just turn it off
1065                     hci_power_control_off();
1066                     break;
1067                 case HCI_POWER_SLEEP:
1068                     // no connections yet, just turn it off
1069                     hci_power_control_sleep();
1070                     break;
1071             }
1072             break;
1073 
1074         case HCI_STATE_WORKING:
1075             switch (power_mode){
1076                 case HCI_POWER_ON:
1077                     // do nothing
1078                     break;
1079                 case HCI_POWER_OFF:
1080                     // see hci_run
1081                     hci_stack.state = HCI_STATE_HALTING;
1082                     break;
1083                 case HCI_POWER_SLEEP:
1084                     // see hci_run
1085                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
1086                     hci_stack.substate = 0;
1087                     break;
1088             }
1089             break;
1090 
1091         case HCI_STATE_HALTING:
1092             switch (power_mode){
1093                 case HCI_POWER_ON:
1094                     // set up state machine
1095                     hci_stack.state = HCI_STATE_INITIALIZING;
1096                     hci_stack.substate = 0;
1097                     break;
1098                 case HCI_POWER_OFF:
1099                     // do nothing
1100                     break;
1101                 case HCI_POWER_SLEEP:
1102                     // see hci_run
1103                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
1104                     hci_stack.substate = 0;
1105                     break;
1106             }
1107             break;
1108 
1109         case HCI_STATE_FALLING_ASLEEP:
1110             switch (power_mode){
1111                 case HCI_POWER_ON:
1112 
1113 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1114                     // nothing to do, if H4 supports power management
1115                     if (bt_control_iphone_power_management_enabled()){
1116                         hci_stack.state = HCI_STATE_INITIALIZING;
1117                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1118                         break;
1119                     }
1120 #endif
1121                     // set up state machine
1122                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1123                     hci_stack.state = HCI_STATE_INITIALIZING;
1124                     hci_stack.substate = 0;
1125                     break;
1126                 case HCI_POWER_OFF:
1127                     // see hci_run
1128                     hci_stack.state = HCI_STATE_HALTING;
1129                     break;
1130                 case HCI_POWER_SLEEP:
1131                     // do nothing
1132                     break;
1133             }
1134             break;
1135 
1136         case HCI_STATE_SLEEPING:
1137             switch (power_mode){
1138                 case HCI_POWER_ON:
1139 
1140 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1141                     // nothing to do, if H4 supports power management
1142                     if (bt_control_iphone_power_management_enabled()){
1143                         hci_stack.state = HCI_STATE_INITIALIZING;
1144                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1145                         hci_update_scan_enable();
1146                         break;
1147                     }
1148 #endif
1149                     err = hci_power_control_wake();
1150                     if (err) return err;
1151                     // set up state machine
1152                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1153                     hci_stack.state = HCI_STATE_INITIALIZING;
1154                     hci_stack.substate = 0;
1155                     break;
1156                 case HCI_POWER_OFF:
1157                     hci_stack.state = HCI_STATE_HALTING;
1158                     break;
1159                 case HCI_POWER_SLEEP:
1160                     // do nothing
1161                     break;
1162             }
1163             break;
1164     }
1165 
1166     // create internal event
1167 	hci_emit_state();
1168 
1169 	// trigger next/first action
1170 	hci_run();
1171 
1172     return 0;
1173 }
1174 
1175 static void hci_update_scan_enable(void){
1176     // 2 = page scan, 1 = inq scan
1177     hci_stack.new_scan_enable_value  = hci_stack.connectable << 1 | hci_stack.discoverable;
1178     hci_run();
1179 }
1180 
1181 void hci_discoverable_control(uint8_t enable){
1182     if (enable) enable = 1; // normalize argument
1183 
1184     if (hci_stack.discoverable == enable){
1185         hci_emit_discoverable_enabled(hci_stack.discoverable);
1186         return;
1187     }
1188 
1189     hci_stack.discoverable = enable;
1190     hci_update_scan_enable();
1191 }
1192 
1193 void hci_connectable_control(uint8_t enable){
1194     if (enable) enable = 1; // normalize argument
1195 
1196     // don't emit event
1197     if (hci_stack.connectable == enable) return;
1198 
1199     hci_stack.connectable = enable;
1200     hci_update_scan_enable();
1201 }
1202 
1203 bd_addr_t * hci_local_bd_addr(void){
1204     return &hci_stack.local_bd_addr;
1205 }
1206 
1207 void hci_run(){
1208 
1209     hci_connection_t * connection;
1210     linked_item_t * it;
1211 
1212     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1213 
1214     // global/non-connection oriented commands
1215 
1216     // decline incoming connections
1217     if (hci_stack.decline_reason){
1218         uint8_t reason = hci_stack.decline_reason;
1219         hci_stack.decline_reason = 0;
1220         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
1221         return;
1222     }
1223 
1224     // send scan enable
1225     if (hci_stack.state == HCI_STATE_WORKING && hci_stack.new_scan_enable_value != 0xff && hci_classic_supported()){
1226         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
1227         hci_stack.new_scan_enable_value = 0xff;
1228         return;
1229     }
1230 
1231     // send pending HCI commands
1232     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
1233 
1234         connection = (hci_connection_t *) it;
1235 
1236         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1237             log_info("sending hci_accept_connection_request\n");
1238             connection->state = ACCEPTED_CONNECTION_REQUEST;
1239             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1240             return;
1241         }
1242 
1243         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1244             log_info("responding to link key request\n");
1245             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1246             link_key_t link_key;
1247             link_key_type_t link_key_type;
1248             if ( hci_stack.remote_device_db
1249               && hci_stack.remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1250               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1251                connection->link_key_type = link_key_type;
1252                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1253             } else {
1254                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1255             }
1256             return;
1257         }
1258 
1259         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1260             log_info("denying to pin request\n");
1261             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1262             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1263             return;
1264         }
1265 
1266         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1267             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1268             if (hci_stack.bondable && hci_stack.ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
1269                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack.ssp_io_capability, NULL, hci_stack.ssp_authentication_requirement);
1270             } else {
1271                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1272             }
1273             return;
1274         }
1275 
1276         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1277             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1278             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1279             return;
1280         }
1281 
1282         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1283             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1284             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1285             return;
1286         }
1287 
1288         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1289             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1290             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1291             return;
1292         }
1293 
1294         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1295             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1296             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1297             return;
1298         }
1299         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1300             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1301             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1302             return;
1303         }
1304         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1305             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1306             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1307             return;
1308         }
1309     }
1310 
1311     switch (hci_stack.state){
1312         case HCI_STATE_INITIALIZING:
1313             // log_info("hci_init: substate %u\n", hci_stack.substate);
1314             if (hci_stack.substate % 2) {
1315                 // odd: waiting for command completion
1316                 return;
1317             }
1318             switch (hci_stack.substate >> 1){
1319                 case 0: // RESET
1320                     hci_send_cmd(&hci_reset);
1321 
1322                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1323                         // skip baud change
1324                         hci_stack.substate = 4; // >> 1 = 2
1325                     }
1326                     break;
1327                 case 1: // SEND BAUD CHANGE
1328                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
1329                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1330                     break;
1331                 case 2: // LOCAL BAUD CHANGE
1332                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1333                     hci_stack.substate += 2;
1334                     // break missing here for fall through
1335 
1336                 case 3:
1337                     // Custom initialization
1338                     if (hci_stack.control && hci_stack.control->next_cmd){
1339                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1340                         if (valid_cmd){
1341                             int size = 3 + hci_stack.hci_packet_buffer[2];
1342                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1343                             hci_stack.substate = 4; // more init commands
1344                             break;
1345                         }
1346                         log_info("hci_run: init script done\n\r");
1347                     }
1348                     // otherwise continue
1349 					hci_send_cmd(&hci_read_bd_addr);
1350 					break;
1351 				case 4:
1352 					hci_send_cmd(&hci_read_buffer_size);
1353 					break;
1354                 case 5:
1355                     hci_send_cmd(&hci_read_local_supported_features);
1356                     break;
1357                 case 6:
1358                     if (hci_le_supported()){
1359                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1360                     } else {
1361                         // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1362                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1363                     }
1364 
1365                     // skip Classic init commands for LE only chipsets
1366                     if (!hci_classic_supported()){
1367                         if (hci_le_supported()){
1368                             hci_stack.substate = 11 << 1;    // skip all classic command
1369                         } else {
1370                             log_error("Neither BR/EDR nor LE supported");
1371                             hci_stack.substate = 13 << 1;    // skip all
1372                         }
1373                     }
1374                     break;
1375                 case 7:
1376                     if (hci_ssp_supported()){
1377                         hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack.ssp_enable);
1378                         break;
1379                     }
1380                     hci_stack.substate += 2;
1381                     // break missing here for fall through
1382 
1383                 case 8:
1384                     // ca. 15 sec
1385                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1386                     break;
1387                 case 9:
1388                     hci_send_cmd(&hci_write_class_of_device, hci_stack.class_of_device);
1389                     break;
1390                 case 10:
1391                     if (hci_stack.local_name){
1392                         hci_send_cmd(&hci_write_local_name, hci_stack.local_name);
1393                     } else {
1394                         char hostname[30];
1395 #ifdef EMBEDDED
1396                         // BTstack-11:22:33:44:55:66
1397                         strcpy(hostname, "BTstack ");
1398                         strcat(hostname, bd_addr_to_str(hci_stack.local_bd_addr));
1399                         printf("---> Name %s\n", hostname);
1400 #else
1401                         // hostname for POSIX systems
1402                         gethostname(hostname, 30);
1403                         hostname[29] = '\0';
1404 #endif
1405                         hci_send_cmd(&hci_write_local_name, hostname);
1406                     }
1407                     break;
1408                 case 11:
1409 					hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan
1410                     if (!hci_le_supported()){
1411                         // SKIP LE init for Classic only configuration
1412                         hci_stack.substate = 13 << 1;
1413                     }
1414 					break;
1415 
1416 #ifdef HAVE_BLE
1417                 // LE INIT
1418                 case 12:
1419                     hci_send_cmd(&hci_le_read_buffer_size);
1420                     break;
1421                 case 13:
1422                     // LE Supported Host = 1, Simultaneous Host = 0
1423                     hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1424                     break;
1425 #endif
1426 
1427                 // DONE
1428                 case 14:
1429                     // done.
1430                     hci_stack.state = HCI_STATE_WORKING;
1431                     hci_emit_state();
1432                     break;
1433                 default:
1434                     break;
1435             }
1436             hci_stack.substate++;
1437             break;
1438 
1439         case HCI_STATE_HALTING:
1440 
1441             log_info("HCI_STATE_HALTING\n");
1442             // close all open connections
1443             connection =  (hci_connection_t *) hci_stack.connections;
1444             if (connection){
1445 
1446                 // send disconnect
1447                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1448 
1449                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1450                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1451 
1452                 // send disconnected event right away - causes higher layer connections to get closed, too.
1453                 hci_shutdown_connection(connection);
1454                 return;
1455             }
1456             log_info("HCI_STATE_HALTING, calling off\n");
1457 
1458             // switch mode
1459             hci_power_control_off();
1460 
1461             log_info("HCI_STATE_HALTING, emitting state\n");
1462             hci_emit_state();
1463             log_info("HCI_STATE_HALTING, done\n");
1464             break;
1465 
1466         case HCI_STATE_FALLING_ASLEEP:
1467             switch(hci_stack.substate) {
1468                 case 0:
1469                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1470                     // close all open connections
1471                     connection =  (hci_connection_t *) hci_stack.connections;
1472 
1473 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1474                     // don't close connections, if H4 supports power management
1475                     if (bt_control_iphone_power_management_enabled()){
1476                         connection = NULL;
1477                     }
1478 #endif
1479                     if (connection){
1480 
1481                         // send disconnect
1482                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1483 
1484                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1485                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1486 
1487                         // send disconnected event right away - causes higher layer connections to get closed, too.
1488                         hci_shutdown_connection(connection);
1489                         return;
1490                     }
1491 
1492                     if (hci_classic_supported()){
1493                         // disable page and inquiry scan
1494                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1495 
1496                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
1497                         hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan
1498 
1499                         // continue in next sub state
1500                         hci_stack.substate++;
1501                         break;
1502                     }
1503                     // fall through for ble-only chips
1504 
1505                 case 2:
1506                     log_info("HCI_STATE_HALTING, calling sleep\n");
1507 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1508                     // don't actually go to sleep, if H4 supports power management
1509                     if (bt_control_iphone_power_management_enabled()){
1510                         // SLEEP MODE reached
1511                         hci_stack.state = HCI_STATE_SLEEPING;
1512                         hci_emit_state();
1513                         break;
1514                     }
1515 #endif
1516                     // switch mode
1517                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1518                     hci_emit_state();
1519                     break;
1520 
1521                 default:
1522                     break;
1523             }
1524             break;
1525 
1526         default:
1527             break;
1528     }
1529 }
1530 
1531 int hci_send_cmd_packet(uint8_t *packet, int size){
1532     bd_addr_t addr;
1533     hci_connection_t * conn;
1534     // house-keeping
1535 
1536     // create_connection?
1537     if (IS_COMMAND(packet, hci_create_connection)){
1538         bt_flip_addr(addr, &packet[3]);
1539         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1540         conn = connection_for_address(addr);
1541         if (conn) {
1542             // if connection exists
1543             if (conn->state == OPEN) {
1544                 // and OPEN, emit connection complete command
1545                 hci_emit_connection_complete(conn, 0);
1546             }
1547             //    otherwise, just ignore as it is already in the open process
1548             return 0; // don't sent packet to controller
1549 
1550         }
1551         // create connection struct and register, state = SENT_CREATE_CONNECTION
1552         conn = create_connection_for_addr(addr);
1553         if (!conn){
1554             // notify client that alloc failed
1555             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1556             return 0; // don't sent packet to controller
1557         }
1558         conn->state = SENT_CREATE_CONNECTION;
1559     }
1560 
1561     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1562         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1563     }
1564     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1565         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1566     }
1567 
1568     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1569         if (hci_stack.remote_device_db){
1570             bt_flip_addr(addr, &packet[3]);
1571             hci_stack.remote_device_db->delete_link_key(&addr);
1572         }
1573     }
1574 
1575     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
1576     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
1577         bt_flip_addr(addr, &packet[3]);
1578         conn = connection_for_address(addr);
1579         if (conn){
1580             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
1581         }
1582     }
1583 
1584     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
1585     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
1586     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
1587     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
1588         bt_flip_addr(addr, &packet[3]);
1589         conn = connection_for_address(addr);
1590         if (conn){
1591             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
1592         }
1593     }
1594 
1595 #ifdef HAVE_BLE
1596     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
1597         hci_stack.adv_addr_type = packet[8];
1598     }
1599     if (IS_COMMAND(packet, hci_le_set_random_address)){
1600         bt_flip_addr(hci_stack.adv_address, &packet[3]);
1601     }
1602 #endif
1603 
1604 
1605     hci_stack.num_cmd_packets--;
1606     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1607 }
1608 
1609 // disconnect because of security block
1610 void hci_disconnect_security_block(hci_con_handle_t con_handle){
1611     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1612     if (!connection) return;
1613     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
1614 }
1615 
1616 
1617 // Configure Secure Simple Pairing
1618 
1619 // enable will enable SSP during init
1620 void hci_ssp_set_enable(int enable){
1621     hci_stack.ssp_enable = enable;
1622 }
1623 
1624 int hci_local_ssp_activated(){
1625     return hci_ssp_supported() && hci_stack.ssp_enable;
1626 }
1627 
1628 // if set, BTstack will respond to io capability request using authentication requirement
1629 void hci_ssp_set_io_capability(int io_capability){
1630     hci_stack.ssp_io_capability = io_capability;
1631 }
1632 void hci_ssp_set_authentication_requirement(int authentication_requirement){
1633     hci_stack.ssp_authentication_requirement = authentication_requirement;
1634 }
1635 
1636 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1637 void hci_ssp_set_auto_accept(int auto_accept){
1638     hci_stack.ssp_auto_accept = auto_accept;
1639 }
1640 
1641 /**
1642  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1643  */
1644 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1645     va_list argptr;
1646     va_start(argptr, cmd);
1647     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1648     va_end(argptr);
1649     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1650 }
1651 
1652 // Create various non-HCI events.
1653 // TODO: generalize, use table similar to hci_create_command
1654 
1655 void hci_emit_state(){
1656     log_info("BTSTACK_EVENT_STATE %u", hci_stack.state);
1657     uint8_t event[3];
1658     event[0] = BTSTACK_EVENT_STATE;
1659     event[1] = sizeof(event) - 2;
1660     event[2] = hci_stack.state;
1661     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1662     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1663 }
1664 
1665 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1666     uint8_t event[13];
1667     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1668     event[1] = sizeof(event) - 2;
1669     event[2] = status;
1670     bt_store_16(event, 3, conn->con_handle);
1671     bt_flip_addr(&event[5], conn->address);
1672     event[11] = 1; // ACL connection
1673     event[12] = 0; // encryption disabled
1674     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1675     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1676 }
1677 
1678 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1679     uint8_t event[6];
1680     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1681     event[1] = sizeof(event) - 2;
1682     event[2] = 0; // status = OK
1683     bt_store_16(event, 3, handle);
1684     event[5] = reason;
1685     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1686     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1687 }
1688 
1689 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1690     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1691     uint8_t event[4];
1692     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1693     event[1] = sizeof(event) - 2;
1694     bt_store_16(event, 2, conn->con_handle);
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 void hci_emit_nr_connections_changed(){
1700     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1701     uint8_t event[3];
1702     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1703     event[1] = sizeof(event) - 2;
1704     event[2] = nr_hci_connections();
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_hci_open_failed(){
1710     log_info("BTSTACK_EVENT_POWERON_FAILED");
1711     uint8_t event[2];
1712     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1713     event[1] = sizeof(event) - 2;
1714     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1715     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1716 }
1717 
1718 #ifndef EMBEDDED
1719 void hci_emit_btstack_version() {
1720     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1721     uint8_t event[6];
1722     event[0] = BTSTACK_EVENT_VERSION;
1723     event[1] = sizeof(event) - 2;
1724     event[2] = BTSTACK_MAJOR;
1725     event[3] = BTSTACK_MINOR;
1726     bt_store_16(event, 4, BTSTACK_REVISION);
1727     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1728     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1729 }
1730 #endif
1731 
1732 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1733     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1734     uint8_t event[3];
1735     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1736     event[1] = sizeof(event) - 2;
1737     event[2] = enabled;
1738     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1739     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1740 }
1741 
1742 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1743     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1744     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1745     event[1] = sizeof(event) - 2 - 1;
1746     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1747     bt_flip_addr(&event[3], *addr);
1748     memcpy(&event[9], name, 248);
1749 
1750     event[9+248] = 0;   // assert \0 for log_info
1751     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
1752 
1753     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
1754     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
1755 }
1756 
1757 void hci_emit_discoverable_enabled(uint8_t enabled){
1758     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
1759     uint8_t event[3];
1760     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1761     event[1] = sizeof(event) - 2;
1762     event[2] = enabled;
1763     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1764     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1765 }
1766 
1767 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
1768     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
1769     uint8_t event[5];
1770     int pos = 0;
1771     event[pos++] = GAP_SECURITY_LEVEL;
1772     event[pos++] = sizeof(event) - 2;
1773     bt_store_16(event, 2, con_handle);
1774     pos += 2;
1775     event[pos++] = level;
1776     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1777     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1778 }
1779 
1780 // query if remote side supports SSP
1781 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
1782     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1783     if (!connection) return 0;
1784     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
1785 }
1786 
1787 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
1788     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
1789 }
1790 
1791 // GAP API
1792 /**
1793  * @bbrief enable/disable bonding. default is enabled
1794  * @praram enabled
1795  */
1796 void gap_set_bondable_mode(int enable){
1797     hci_stack.bondable = enable ? 1 : 0;
1798 }
1799 
1800 /**
1801  * @brief map link keys to security levels
1802  */
1803 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
1804     switch (link_key_type){
1805         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
1806             return LEVEL_4;
1807         case COMBINATION_KEY:
1808         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
1809             return LEVEL_3;
1810         default:
1811             return LEVEL_2;
1812     }
1813 }
1814 
1815 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
1816     if (!connection) return LEVEL_0;
1817     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
1818     return gap_security_level_for_link_key_type(connection->link_key_type);
1819 }
1820 
1821 
1822 /**
1823  * @brief get current security level
1824  */
1825 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
1826     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1827     if (!connection) return LEVEL_0;
1828     return gap_security_level_for_connection(connection);
1829 }
1830 
1831 /**
1832  * @brief request connection to device to
1833  * @result GAP_AUTHENTICATION_RESULT
1834  */
1835 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
1836     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1837     if (!connection){
1838         hci_emit_security_level(con_handle, LEVEL_0);
1839         return;
1840     }
1841     gap_security_level_t current_level = gap_security_level(con_handle);
1842     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
1843     if (current_level >= requested_level){
1844         hci_emit_security_level(con_handle, current_level);
1845         return;
1846     }
1847 
1848     connection->requested_security_level = requested_level;
1849 
1850     // would enabling ecnryption suffice (>= LEVEL_2)?
1851     if (hci_stack.remote_device_db){
1852         link_key_type_t link_key_type;
1853         link_key_t      link_key;
1854         if (hci_stack.remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
1855             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
1856                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1857                 return;
1858             }
1859         }
1860     }
1861 
1862     // setup SSP AuthRequirements, we need MITM to go higher
1863     hci_stack.ssp_authentication_requirement |= 1;  // MITM required
1864 
1865     // try to authenticate connection
1866     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1867 }
1868