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