xref: /btstack/src/hci.c (revision 9e61646f3e01344295c409f671fb308c3b85edf2)
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 void hci_set_class_of_device(uint32_t class_of_device){
969     hci_stack->class_of_device = class_of_device;
970 }
971 
972 // State-Module-Driver overview
973 // state                    module  low-level
974 // HCI_STATE_OFF             off      close
975 // HCI_STATE_INITIALIZING,   on       open
976 // HCI_STATE_WORKING,        on       open
977 // HCI_STATE_HALTING,        on       open
978 // HCI_STATE_SLEEPING,    off/sleep   close
979 // HCI_STATE_FALLING_ASLEEP  on       open
980 
981 static int hci_power_control_on(void){
982 
983     // power on
984     int err = 0;
985     if (hci_stack->control && hci_stack->control->on){
986         err = (*hci_stack->control->on)(hci_stack->config);
987     }
988     if (err){
989         log_error( "POWER_ON failed\n");
990         hci_emit_hci_open_failed();
991         return err;
992     }
993 
994     // open low-level device
995     err = hci_stack->hci_transport->open(hci_stack->config);
996     if (err){
997         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
998         if (hci_stack->control && hci_stack->control->off){
999             (*hci_stack->control->off)(hci_stack->config);
1000         }
1001         hci_emit_hci_open_failed();
1002         return err;
1003     }
1004     return 0;
1005 }
1006 
1007 static void hci_power_control_off(void){
1008 
1009     log_info("hci_power_control_off\n");
1010 
1011     // close low-level device
1012     hci_stack->hci_transport->close(hci_stack->config);
1013 
1014     log_info("hci_power_control_off - hci_transport closed\n");
1015 
1016     // power off
1017     if (hci_stack->control && hci_stack->control->off){
1018         (*hci_stack->control->off)(hci_stack->config);
1019     }
1020 
1021     log_info("hci_power_control_off - control closed\n");
1022 
1023     hci_stack->state = HCI_STATE_OFF;
1024 }
1025 
1026 static void hci_power_control_sleep(void){
1027 
1028     log_info("hci_power_control_sleep\n");
1029 
1030 #if 0
1031     // don't close serial port during sleep
1032 
1033     // close low-level device
1034     hci_stack->hci_transport->close(hci_stack->config);
1035 #endif
1036 
1037     // sleep mode
1038     if (hci_stack->control && hci_stack->control->sleep){
1039         (*hci_stack->control->sleep)(hci_stack->config);
1040     }
1041 
1042     hci_stack->state = HCI_STATE_SLEEPING;
1043 }
1044 
1045 static int hci_power_control_wake(void){
1046 
1047     log_info("hci_power_control_wake\n");
1048 
1049     // wake on
1050     if (hci_stack->control && hci_stack->control->wake){
1051         (*hci_stack->control->wake)(hci_stack->config);
1052     }
1053 
1054 #if 0
1055     // open low-level device
1056     int err = hci_stack->hci_transport->open(hci_stack->config);
1057     if (err){
1058         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
1059         if (hci_stack->control && hci_stack->control->off){
1060             (*hci_stack->control->off)(hci_stack->config);
1061         }
1062         hci_emit_hci_open_failed();
1063         return err;
1064     }
1065 #endif
1066 
1067     return 0;
1068 }
1069 
1070 
1071 int hci_power_control(HCI_POWER_MODE power_mode){
1072 
1073     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack->state);
1074 
1075     int err = 0;
1076     switch (hci_stack->state){
1077 
1078         case HCI_STATE_OFF:
1079             switch (power_mode){
1080                 case HCI_POWER_ON:
1081                     err = hci_power_control_on();
1082                     if (err) return err;
1083                     // set up state machine
1084                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1085                     hci_stack->state = HCI_STATE_INITIALIZING;
1086                     hci_stack->substate = 0;
1087                     break;
1088                 case HCI_POWER_OFF:
1089                     // do nothing
1090                     break;
1091                 case HCI_POWER_SLEEP:
1092                     // do nothing (with SLEEP == OFF)
1093                     break;
1094             }
1095             break;
1096 
1097         case HCI_STATE_INITIALIZING:
1098             switch (power_mode){
1099                 case HCI_POWER_ON:
1100                     // do nothing
1101                     break;
1102                 case HCI_POWER_OFF:
1103                     // no connections yet, just turn it off
1104                     hci_power_control_off();
1105                     break;
1106                 case HCI_POWER_SLEEP:
1107                     // no connections yet, just turn it off
1108                     hci_power_control_sleep();
1109                     break;
1110             }
1111             break;
1112 
1113         case HCI_STATE_WORKING:
1114             switch (power_mode){
1115                 case HCI_POWER_ON:
1116                     // do nothing
1117                     break;
1118                 case HCI_POWER_OFF:
1119                     // see hci_run
1120                     hci_stack->state = HCI_STATE_HALTING;
1121                     break;
1122                 case HCI_POWER_SLEEP:
1123                     // see hci_run
1124                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1125                     hci_stack->substate = 0;
1126                     break;
1127             }
1128             break;
1129 
1130         case HCI_STATE_HALTING:
1131             switch (power_mode){
1132                 case HCI_POWER_ON:
1133                     // set up state machine
1134                     hci_stack->state = HCI_STATE_INITIALIZING;
1135                     hci_stack->substate = 0;
1136                     break;
1137                 case HCI_POWER_OFF:
1138                     // do nothing
1139                     break;
1140                 case HCI_POWER_SLEEP:
1141                     // see hci_run
1142                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1143                     hci_stack->substate = 0;
1144                     break;
1145             }
1146             break;
1147 
1148         case HCI_STATE_FALLING_ASLEEP:
1149             switch (power_mode){
1150                 case HCI_POWER_ON:
1151 
1152 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1153                     // nothing to do, if H4 supports power management
1154                     if (bt_control_iphone_power_management_enabled()){
1155                         hci_stack->state = HCI_STATE_INITIALIZING;
1156                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1157                         break;
1158                     }
1159 #endif
1160                     // set up state machine
1161                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1162                     hci_stack->state = HCI_STATE_INITIALIZING;
1163                     hci_stack->substate = 0;
1164                     break;
1165                 case HCI_POWER_OFF:
1166                     // see hci_run
1167                     hci_stack->state = HCI_STATE_HALTING;
1168                     break;
1169                 case HCI_POWER_SLEEP:
1170                     // do nothing
1171                     break;
1172             }
1173             break;
1174 
1175         case HCI_STATE_SLEEPING:
1176             switch (power_mode){
1177                 case HCI_POWER_ON:
1178 
1179 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1180                     // nothing to do, if H4 supports power management
1181                     if (bt_control_iphone_power_management_enabled()){
1182                         hci_stack->state = HCI_STATE_INITIALIZING;
1183                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1184                         hci_update_scan_enable();
1185                         break;
1186                     }
1187 #endif
1188                     err = hci_power_control_wake();
1189                     if (err) return err;
1190                     // set up state machine
1191                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1192                     hci_stack->state = HCI_STATE_INITIALIZING;
1193                     hci_stack->substate = 0;
1194                     break;
1195                 case HCI_POWER_OFF:
1196                     hci_stack->state = HCI_STATE_HALTING;
1197                     break;
1198                 case HCI_POWER_SLEEP:
1199                     // do nothing
1200                     break;
1201             }
1202             break;
1203     }
1204 
1205     // create internal event
1206 	hci_emit_state();
1207 
1208 	// trigger next/first action
1209 	hci_run();
1210 
1211     return 0;
1212 }
1213 
1214 static void hci_update_scan_enable(void){
1215     // 2 = page scan, 1 = inq scan
1216     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1217     hci_run();
1218 }
1219 
1220 void hci_discoverable_control(uint8_t enable){
1221     if (enable) enable = 1; // normalize argument
1222 
1223     if (hci_stack->discoverable == enable){
1224         hci_emit_discoverable_enabled(hci_stack->discoverable);
1225         return;
1226     }
1227 
1228     hci_stack->discoverable = enable;
1229     hci_update_scan_enable();
1230 }
1231 
1232 void hci_connectable_control(uint8_t enable){
1233     if (enable) enable = 1; // normalize argument
1234 
1235     // don't emit event
1236     if (hci_stack->connectable == enable) return;
1237 
1238     hci_stack->connectable = enable;
1239     hci_update_scan_enable();
1240 }
1241 
1242 bd_addr_t * hci_local_bd_addr(void){
1243     return &hci_stack->local_bd_addr;
1244 }
1245 
1246 void hci_run(){
1247 
1248     hci_connection_t * connection;
1249     linked_item_t * it;
1250 
1251     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1252 
1253     // global/non-connection oriented commands
1254 
1255     // decline incoming connections
1256     if (hci_stack->decline_reason){
1257         uint8_t reason = hci_stack->decline_reason;
1258         hci_stack->decline_reason = 0;
1259         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1260         return;
1261     }
1262 
1263     // send scan enable
1264     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1265         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1266         hci_stack->new_scan_enable_value = 0xff;
1267         return;
1268     }
1269 
1270     // send pending HCI commands
1271     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1272 
1273         connection = (hci_connection_t *) it;
1274 
1275         if (connection->state == SEND_CREATE_CONNECTION){
1276             log_info("sending hci_create_connection\n");
1277             hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1278             return;
1279         }
1280 
1281         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1282             log_info("sending hci_accept_connection_request\n");
1283             connection->state = ACCEPTED_CONNECTION_REQUEST;
1284             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1285             return;
1286         }
1287 
1288         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1289             log_info("responding to link key request\n");
1290             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1291             link_key_t link_key;
1292             link_key_type_t link_key_type;
1293             if ( hci_stack->remote_device_db
1294               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1295               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1296                connection->link_key_type = link_key_type;
1297                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1298             } else {
1299                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1300             }
1301             return;
1302         }
1303 
1304         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1305             log_info("denying to pin request\n");
1306             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1307             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1308             return;
1309         }
1310 
1311         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1312             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1313             if (hci_stack->bondable && hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
1314                 // tweak authentication requirements
1315                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1316                 if (connection->bonding_flags & BONDING_DEDICATED){
1317                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1318                 }
1319                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1320                     authreq |= 1;
1321                 }
1322                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1323             } else {
1324                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1325             }
1326             return;
1327         }
1328 
1329         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1330             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1331             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1332             return;
1333         }
1334 
1335         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1336             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1337             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1338             return;
1339         }
1340 
1341         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1342             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1343             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1344             return;
1345         }
1346 
1347         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1348             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1349             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1350             return;
1351         }
1352         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1353             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1354             hci_send_cmd(&hci_disconnect, connection->con_handle, 0);  // authentication done
1355             return;
1356         }
1357         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1358             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1359             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1360             return;
1361         }
1362         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1363             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1364             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1365             return;
1366         }
1367     }
1368 
1369     switch (hci_stack->state){
1370         case HCI_STATE_INITIALIZING:
1371             // log_info("hci_init: substate %u\n", hci_stack->substate);
1372             if (hci_stack->substate % 2) {
1373                 // odd: waiting for command completion
1374                 return;
1375             }
1376             switch (hci_stack->substate >> 1){
1377                 case 0: // RESET
1378                     hci_send_cmd(&hci_reset);
1379 
1380                     if (hci_stack->config == 0 || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
1381                         // skip baud change
1382                         hci_stack->substate = 4; // >> 1 = 2
1383                     }
1384                     break;
1385                 case 1: // SEND BAUD CHANGE
1386                     hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
1387                     hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1388                     break;
1389                 case 2: // LOCAL BAUD CHANGE
1390                     hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
1391                     hci_stack->substate += 2;
1392                     // break missing here for fall through
1393 
1394                 case 3:
1395                     // Custom initialization
1396                     if (hci_stack->control && hci_stack->control->next_cmd){
1397                         int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
1398                         if (valid_cmd){
1399                             int size = 3 + hci_stack->hci_packet_buffer[2];
1400                             hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1401                             hci_stack->substate = 4; // more init commands
1402                             break;
1403                         }
1404                         log_info("hci_run: init script done\n\r");
1405                     }
1406                     // otherwise continue
1407 					hci_send_cmd(&hci_read_bd_addr);
1408 					break;
1409 				case 4:
1410 					hci_send_cmd(&hci_read_buffer_size);
1411 					break;
1412                 case 5:
1413                     hci_send_cmd(&hci_read_local_supported_features);
1414                     break;
1415                 case 6:
1416                     if (hci_le_supported()){
1417                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1418                     } else {
1419                         // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1420                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1421                     }
1422 
1423                     // skip Classic init commands for LE only chipsets
1424                     if (!hci_classic_supported()){
1425                         if (hci_le_supported()){
1426                             hci_stack->substate = 11 << 1;    // skip all classic command
1427                         } else {
1428                             log_error("Neither BR/EDR nor LE supported");
1429                             hci_stack->substate = 13 << 1;    // skip all
1430                         }
1431                     }
1432                     break;
1433                 case 7:
1434                     if (hci_ssp_supported()){
1435                         hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1436                         break;
1437                     }
1438                     hci_stack->substate += 2;
1439                     // break missing here for fall through
1440 
1441                 case 8:
1442                     // ca. 15 sec
1443                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1444                     break;
1445                 case 9:
1446                     hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1447                     break;
1448                 case 10:
1449                     if (hci_stack->local_name){
1450                         hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
1451                     } else {
1452                         char hostname[30];
1453 #ifdef EMBEDDED
1454                         // BTstack-11:22:33:44:55:66
1455                         strcpy(hostname, "BTstack ");
1456                         strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
1457                         printf("---> Name %s\n", hostname);
1458 #else
1459                         // hostname for POSIX systems
1460                         gethostname(hostname, 30);
1461                         hostname[29] = '\0';
1462 #endif
1463                         hci_send_cmd(&hci_write_local_name, hostname);
1464                     }
1465                     break;
1466                 case 11:
1467 					hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1468                     if (!hci_le_supported()){
1469                         // SKIP LE init for Classic only configuration
1470                         hci_stack->substate = 13 << 1;
1471                     }
1472 					break;
1473 
1474 #ifdef HAVE_BLE
1475                 // LE INIT
1476                 case 12:
1477                     hci_send_cmd(&hci_le_read_buffer_size);
1478                     break;
1479                 case 13:
1480                     // LE Supported Host = 1, Simultaneous Host = 0
1481                     hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1482                     break;
1483 #endif
1484 
1485                 // DONE
1486                 case 14:
1487                     // done.
1488                     hci_stack->state = HCI_STATE_WORKING;
1489                     hci_emit_state();
1490                     break;
1491                 default:
1492                     break;
1493             }
1494             hci_stack->substate++;
1495             break;
1496 
1497         case HCI_STATE_HALTING:
1498 
1499             log_info("HCI_STATE_HALTING\n");
1500             // close all open connections
1501             connection =  (hci_connection_t *) hci_stack->connections;
1502             if (connection){
1503 
1504                 // send disconnect
1505                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1506 
1507                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1508                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1509 
1510                 // send disconnected event right away - causes higher layer connections to get closed, too.
1511                 hci_shutdown_connection(connection);
1512                 return;
1513             }
1514             log_info("HCI_STATE_HALTING, calling off\n");
1515 
1516             // switch mode
1517             hci_power_control_off();
1518 
1519             log_info("HCI_STATE_HALTING, emitting state\n");
1520             hci_emit_state();
1521             log_info("HCI_STATE_HALTING, done\n");
1522             break;
1523 
1524         case HCI_STATE_FALLING_ASLEEP:
1525             switch(hci_stack->substate) {
1526                 case 0:
1527                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1528                     // close all open connections
1529                     connection =  (hci_connection_t *) hci_stack->connections;
1530 
1531 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1532                     // don't close connections, if H4 supports power management
1533                     if (bt_control_iphone_power_management_enabled()){
1534                         connection = NULL;
1535                     }
1536 #endif
1537                     if (connection){
1538 
1539                         // send disconnect
1540                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1541 
1542                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1543                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1544 
1545                         // send disconnected event right away - causes higher layer connections to get closed, too.
1546                         hci_shutdown_connection(connection);
1547                         return;
1548                     }
1549 
1550                     if (hci_classic_supported()){
1551                         // disable page and inquiry scan
1552                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1553 
1554                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
1555                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
1556 
1557                         // continue in next sub state
1558                         hci_stack->substate++;
1559                         break;
1560                     }
1561                     // fall through for ble-only chips
1562 
1563                 case 2:
1564                     log_info("HCI_STATE_HALTING, calling sleep\n");
1565 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1566                     // don't actually go to sleep, if H4 supports power management
1567                     if (bt_control_iphone_power_management_enabled()){
1568                         // SLEEP MODE reached
1569                         hci_stack->state = HCI_STATE_SLEEPING;
1570                         hci_emit_state();
1571                         break;
1572                     }
1573 #endif
1574                     // switch mode
1575                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
1576                     hci_emit_state();
1577                     break;
1578 
1579                 default:
1580                     break;
1581             }
1582             break;
1583 
1584         default:
1585             break;
1586     }
1587 }
1588 
1589 int hci_send_cmd_packet(uint8_t *packet, int size){
1590     bd_addr_t addr;
1591     hci_connection_t * conn;
1592     // house-keeping
1593 
1594     // create_connection?
1595     if (IS_COMMAND(packet, hci_create_connection)){
1596         bt_flip_addr(addr, &packet[3]);
1597         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1598 
1599         conn = connection_for_address(addr);
1600         if (!conn){
1601             conn = create_connection_for_addr(addr);
1602             if (!conn){
1603                 // notify client that alloc failed
1604                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1605                 return 0; // don't sent packet to controller
1606             }
1607             conn->state = SEND_CREATE_CONNECTION;
1608         }
1609         log_info("conn state %u", conn->state);
1610         switch (conn->state){
1611             // if connection active exists
1612             case OPEN:
1613                 // and OPEN, emit connection complete command
1614                 hci_emit_connection_complete(conn, 0);
1615                 break;
1616             case SEND_CREATE_CONNECTION:
1617                 // connection created by hci, e.g. dedicated bonding
1618                 break;
1619             default:
1620                 // otherwise, just ignore as it is already in the open process
1621                 return 0;
1622         }
1623         conn->state = SENT_CREATE_CONNECTION;
1624     }
1625 
1626     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1627         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1628     }
1629     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1630         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1631     }
1632 
1633     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1634         if (hci_stack->remote_device_db){
1635             bt_flip_addr(addr, &packet[3]);
1636             hci_stack->remote_device_db->delete_link_key(&addr);
1637         }
1638     }
1639 
1640     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
1641     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
1642         bt_flip_addr(addr, &packet[3]);
1643         conn = connection_for_address(addr);
1644         if (conn){
1645             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
1646         }
1647     }
1648 
1649     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
1650     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
1651     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
1652     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
1653         bt_flip_addr(addr, &packet[3]);
1654         conn = connection_for_address(addr);
1655         if (conn){
1656             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
1657         }
1658     }
1659 
1660 #ifdef HAVE_BLE
1661     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
1662         hci_stack->adv_addr_type = packet[8];
1663     }
1664     if (IS_COMMAND(packet, hci_le_set_random_address)){
1665         bt_flip_addr(hci_stack->adv_address, &packet[3]);
1666     }
1667 #endif
1668 
1669 
1670     hci_stack->num_cmd_packets--;
1671     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1672 }
1673 
1674 // disconnect because of security block
1675 void hci_disconnect_security_block(hci_con_handle_t con_handle){
1676     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1677     if (!connection) return;
1678     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
1679 }
1680 
1681 
1682 // Configure Secure Simple Pairing
1683 
1684 // enable will enable SSP during init
1685 void hci_ssp_set_enable(int enable){
1686     hci_stack->ssp_enable = enable;
1687 }
1688 
1689 int hci_local_ssp_activated(){
1690     return hci_ssp_supported() && hci_stack->ssp_enable;
1691 }
1692 
1693 // if set, BTstack will respond to io capability request using authentication requirement
1694 void hci_ssp_set_io_capability(int io_capability){
1695     hci_stack->ssp_io_capability = io_capability;
1696 }
1697 void hci_ssp_set_authentication_requirement(int authentication_requirement){
1698     hci_stack->ssp_authentication_requirement = authentication_requirement;
1699 }
1700 
1701 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1702 void hci_ssp_set_auto_accept(int auto_accept){
1703     hci_stack->ssp_auto_accept = auto_accept;
1704 }
1705 
1706 /**
1707  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1708  */
1709 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1710     va_list argptr;
1711     va_start(argptr, cmd);
1712     uint16_t size = hci_create_cmd_internal(hci_stack->hci_packet_buffer, cmd, argptr);
1713     va_end(argptr);
1714     return hci_send_cmd_packet(hci_stack->hci_packet_buffer, size);
1715 }
1716 
1717 // Create various non-HCI events.
1718 // TODO: generalize, use table similar to hci_create_command
1719 
1720 void hci_emit_state(){
1721     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
1722     uint8_t event[3];
1723     event[0] = BTSTACK_EVENT_STATE;
1724     event[1] = sizeof(event) - 2;
1725     event[2] = hci_stack->state;
1726     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1727     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1728 }
1729 
1730 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1731     uint8_t event[13];
1732     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1733     event[1] = sizeof(event) - 2;
1734     event[2] = status;
1735     bt_store_16(event, 3, conn->con_handle);
1736     bt_flip_addr(&event[5], conn->address);
1737     event[11] = 1; // ACL connection
1738     event[12] = 0; // encryption disabled
1739     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1740     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1741 }
1742 
1743 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1744     uint8_t event[6];
1745     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1746     event[1] = sizeof(event) - 2;
1747     event[2] = 0; // status = OK
1748     bt_store_16(event, 3, handle);
1749     event[5] = reason;
1750     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1751     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1752 }
1753 
1754 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1755     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1756     uint8_t event[4];
1757     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1758     event[1] = sizeof(event) - 2;
1759     bt_store_16(event, 2, conn->con_handle);
1760     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1761     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1762 }
1763 
1764 void hci_emit_nr_connections_changed(){
1765     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1766     uint8_t event[3];
1767     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1768     event[1] = sizeof(event) - 2;
1769     event[2] = nr_hci_connections();
1770     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1771     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1772 }
1773 
1774 void hci_emit_hci_open_failed(){
1775     log_info("BTSTACK_EVENT_POWERON_FAILED");
1776     uint8_t event[2];
1777     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1778     event[1] = sizeof(event) - 2;
1779     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1780     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1781 }
1782 
1783 #ifndef EMBEDDED
1784 void hci_emit_btstack_version() {
1785     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1786     uint8_t event[6];
1787     event[0] = BTSTACK_EVENT_VERSION;
1788     event[1] = sizeof(event) - 2;
1789     event[2] = BTSTACK_MAJOR;
1790     event[3] = BTSTACK_MINOR;
1791     bt_store_16(event, 4, BTSTACK_REVISION);
1792     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1793     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1794 }
1795 #endif
1796 
1797 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1798     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1799     uint8_t event[3];
1800     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1801     event[1] = sizeof(event) - 2;
1802     event[2] = enabled;
1803     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1804     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1805 }
1806 
1807 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1808     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1809     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1810     event[1] = sizeof(event) - 2 - 1;
1811     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1812     bt_flip_addr(&event[3], *addr);
1813     memcpy(&event[9], name, 248);
1814 
1815     event[9+248] = 0;   // assert \0 for log_info
1816     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
1817 
1818     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
1819     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
1820 }
1821 
1822 void hci_emit_discoverable_enabled(uint8_t enabled){
1823     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
1824     uint8_t event[3];
1825     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1826     event[1] = sizeof(event) - 2;
1827     event[2] = enabled;
1828     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1829     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1830 }
1831 
1832 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
1833     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
1834     uint8_t event[5];
1835     int pos = 0;
1836     event[pos++] = GAP_SECURITY_LEVEL;
1837     event[pos++] = sizeof(event) - 2;
1838     bt_store_16(event, 2, con_handle);
1839     pos += 2;
1840     event[pos++] = level;
1841     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1842     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1843 }
1844 
1845 void hci_emit_dedicated_bonding_result(hci_connection_t * connection, uint8_t status){
1846     log_info("hci_emit_dedicated_bonding_result %u ", status);
1847     uint8_t event[9];
1848     int pos = 0;
1849     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
1850     event[pos++] = sizeof(event) - 2;
1851     event[pos++] = status;
1852     bt_flip_addr( * (bd_addr_t *) &event[pos], connection->address);
1853     pos += 6;
1854     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1855     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1856 }
1857 
1858 // query if remote side supports SSP
1859 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
1860     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1861     if (!connection) return 0;
1862     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
1863 }
1864 
1865 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
1866     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
1867 }
1868 
1869 // GAP API
1870 /**
1871  * @bbrief enable/disable bonding. default is enabled
1872  * @praram enabled
1873  */
1874 void gap_set_bondable_mode(int enable){
1875     hci_stack->bondable = enable ? 1 : 0;
1876 }
1877 
1878 /**
1879  * @brief map link keys to security levels
1880  */
1881 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
1882     switch (link_key_type){
1883         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
1884             return LEVEL_4;
1885         case COMBINATION_KEY:
1886         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
1887             return LEVEL_3;
1888         default:
1889             return LEVEL_2;
1890     }
1891 }
1892 
1893 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
1894     if (!connection) return LEVEL_0;
1895     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
1896     return gap_security_level_for_link_key_type(connection->link_key_type);
1897 }
1898 
1899 
1900 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
1901     return level > LEVEL_2;
1902 }
1903 
1904 /**
1905  * @brief get current security level
1906  */
1907 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
1908     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1909     if (!connection) return LEVEL_0;
1910     return gap_security_level_for_connection(connection);
1911 }
1912 
1913 /**
1914  * @brief request connection to device to
1915  * @result GAP_AUTHENTICATION_RESULT
1916  */
1917 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
1918     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1919     if (!connection){
1920         hci_emit_security_level(con_handle, LEVEL_0);
1921         return;
1922     }
1923     gap_security_level_t current_level = gap_security_level(con_handle);
1924     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
1925     if (current_level >= requested_level){
1926         hci_emit_security_level(con_handle, current_level);
1927         return;
1928     }
1929 
1930     connection->requested_security_level = requested_level;
1931 
1932     // would enabling ecnryption suffice (>= LEVEL_2)?
1933     if (hci_stack->remote_device_db){
1934         link_key_type_t link_key_type;
1935         link_key_t      link_key;
1936         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
1937             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
1938                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1939                 return;
1940             }
1941         }
1942     }
1943 
1944     // try to authenticate connection
1945     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1946 }
1947 
1948 /**
1949  * @brief start dedicated bonding with device. disconnect after bonding
1950  * @param device
1951  * @param request MITM protection
1952  * @result GAP_DEDICATED_BONDING_COMPLETE
1953  */
1954 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
1955 
1956 
1957     printf("gap_dedicated_bonding clled\n");
1958     // create connection state machine
1959     hci_connection_t * connection = create_connection_for_addr(device);
1960 
1961     if (!connection){
1962         return BTSTACK_MEMORY_ALLOC_FAILED;
1963     }
1964 
1965     printf("gap_dedicated_bonding 2\n");
1966 
1967     // delete linkn key
1968     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
1969 
1970     // configure LEVEL_2/3, dedicated bonding
1971     connection->state = SEND_CREATE_CONNECTION;
1972     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
1973     connection->bonding_flags = BONDING_DEDICATED;
1974 
1975     // wait for GAP Security Result and send GAP Dedicated Bonding complete
1976 
1977     // handle: connnection failure (connection complete != ok)
1978     // handle: authentication failure
1979     // handle: disconnect on done
1980 
1981     hci_run();
1982 
1983     return 0;
1984 }
1985