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