xref: /btstack/src/hci.c (revision e31f89a78637b76dd1660d659472d4a5a0e215c5)
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_non_flushable_packet_boundary_flag_supported(void){
488     // No. 54, byte 6, bit 6
489     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
490 }
491 
492 int hci_ssp_supported(void){
493     // No. 51, byte 6, bit 3
494     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
495 }
496 
497 int hci_classic_supported(void){
498     // No. 37, byte 4, bit 5, = No BR/EDR Support
499     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
500 }
501 
502 int hci_le_supported(void){
503 #ifdef HAVE_BLE
504     // No. 37, byte 4, bit 6 = LE Supported (Controller)
505     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
506 #else
507     return 0;
508 #endif
509 }
510 
511 // get addr type and address used in advertisement packets
512 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
513     *addr_type = hci_stack->adv_addr_type;
514     if (hci_stack->adv_addr_type){
515         memcpy(addr, hci_stack->adv_address, 6);
516     } else {
517         memcpy(addr, hci_stack->local_bd_addr, 6);
518     }
519 }
520 
521 #ifdef HAVE_BLE
522 static void le_handle_advertisement_report(uint8_t *packet, int size){
523     int num_reports = packet[3];
524     int i;
525     int total_data_length = 0;
526     int data_offset = 0;
527 
528     for (i=0; i<num_reports;i++){
529         total_data_length += packet[4+num_reports*8+i];
530     }
531 
532     for (i=0; i<num_reports;i++){
533         int pos = 0;
534         uint8_t data_length = packet[4+num_reports*8+i];
535         uint8_t event_size = 10 + data_length;
536         uint8_t event[2 + event_size ];
537         event[pos++] = GAP_LE_ADVERTISING_REPORT;
538         event[pos++] = event_size;
539         event[pos++] = packet[4+i]; // event_type;
540         event[pos++] = packet[4+num_reports+i]; // address_type;
541         memcpy(&event[pos], &packet[4+num_reports*2+i*6], 6); // bt address
542         pos += 6;
543         event[pos++] = packet[4+num_reports*9+total_data_length + i];
544         event[pos++] = data_length;
545         memcpy(&packet[4+num_reports*9+data_offset], &event[pos], data_length);
546         data_offset += data_length;
547         pos += data_length;
548         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
549     }
550 }
551 #endif
552 
553 // avoid huge local variables
554 #ifndef EMBEDDED
555 static device_name_t device_name;
556 #endif
557 static void event_handler(uint8_t *packet, int size){
558 
559     uint16_t event_length = packet[1];
560 
561     // assert packet is complete
562     if (size != event_length + 2){
563         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
564         return;
565     }
566 
567     bd_addr_t addr;
568     bd_addr_type_t addr_type;
569     uint8_t link_type;
570     hci_con_handle_t handle;
571     hci_connection_t * conn;
572     int i;
573 
574     // printf("HCI:EVENT:%02x\n", packet[0]);
575 
576     switch (packet[0]) {
577 
578         case HCI_EVENT_COMMAND_COMPLETE:
579             // get num cmd packets
580             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack->num_cmd_packets, packet[2]);
581             hci_stack->num_cmd_packets = packet[2];
582 
583             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
584                 // from offset 5
585                 // status
586                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
587                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
588                 // ignore: SCO data packet len (8)
589                 hci_stack->total_num_acl_packets  = packet[9];
590                 // ignore: total num SCO packets
591                 if (hci_stack->state == HCI_STATE_INITIALIZING){
592                     // determine usable ACL payload size
593                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
594                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
595                     }
596                     log_info("hci_read_buffer_size: used size %u, count %u\n",
597                              hci_stack->acl_data_packet_length, hci_stack->total_num_acl_packets);
598                 }
599             }
600 #ifdef HAVE_BLE
601             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
602                 hci_stack->le_data_packet_length = READ_BT_16(packet, 6);
603                 hci_stack->total_num_le_packets  = packet[8];
604                 log_info("hci_le_read_buffer_size: size %u, count %u\n", hci_stack->le_data_packet_length, hci_stack->total_num_le_packets);
605 
606                 // use LE buffers if no clasic buffers have been reported
607                 if (hci_stack->total_num_acl_packets == 0){
608                     log_info("use le buffers instead of classic ones");
609                     hci_stack->total_num_acl_packets  = hci_stack->total_num_le_packets;
610                     hci_stack->acl_data_packet_length = hci_stack->le_data_packet_length;
611                     // determine usable ACL payload size
612                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
613                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
614                     }
615                 }
616             }
617 #endif
618             // Dump local address
619             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
620                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
621                 log_info("Local Address, Status: 0x%02x: Addr: %s\n",
622                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
623             }
624             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
625                 hci_emit_discoverable_enabled(hci_stack->discoverable);
626             }
627             // Note: HCI init checks
628             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
629                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
630                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
631                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
632                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
633                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
634                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
635 
636                 // determine usable ACL packet types based buffer size and supported features
637                 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]);
638                 log_info("packet types %04x", hci_stack->packet_types);
639 
640                 // Classic/LE
641                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
642             }
643             break;
644 
645         case HCI_EVENT_COMMAND_STATUS:
646             // get num cmd packets
647             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack->num_cmd_packets, packet[3]);
648             hci_stack->num_cmd_packets = packet[3];
649             break;
650 
651         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
652             for (i=0; i<packet[2];i++){
653                 handle = READ_BT_16(packet, 3 + 2*i);
654                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
655                 conn = hci_connection_for_handle(handle);
656                 if (!conn){
657                     log_error("hci_number_completed_packet lists unused con handle %u\n", handle);
658                     continue;
659                 }
660                 conn->num_acl_packets_sent -= num_packets;
661                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
662             }
663             break;
664 
665         case HCI_EVENT_CONNECTION_REQUEST:
666             bt_flip_addr(addr, &packet[2]);
667             // TODO: eval COD 8-10
668             link_type = packet[11];
669             log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type);
670             if (link_type == 1) { // ACL
671                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
672                 if (!conn) {
673                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
674                 }
675                 if (!conn) {
676                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
677                     hci_stack->decline_reason = 0x0d;
678                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
679                     break;
680                 }
681                 conn->state = RECEIVED_CONNECTION_REQUEST;
682                 hci_run();
683             } else {
684                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
685                 hci_stack->decline_reason = 0x0a;
686                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
687             }
688             break;
689 
690         case HCI_EVENT_CONNECTION_COMPLETE:
691             // Connection management
692             bt_flip_addr(addr, &packet[5]);
693             log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr));
694             addr_type = BD_ADDR_TYPE_CLASSIC;
695             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
696             if (conn) {
697                 if (!packet[2]){
698                     conn->state = OPEN;
699                     conn->con_handle = READ_BT_16(packet, 3);
700                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
701 
702                     // restart timer
703                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
704                     run_loop_add_timer(&conn->timeout);
705 
706                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
707 
708                     hci_emit_nr_connections_changed();
709                 } else {
710                     // notify client if dedicated bonding
711                     if (conn->bonding_flags & BONDING_DEDICATED){
712                         hci_emit_dedicated_bonding_result(conn, packet[2]);
713                     }
714 
715                     // connection failed, remove entry
716                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
717                     btstack_memory_hci_connection_free( conn );
718 
719                     // if authentication error, also delete link key
720                     if (packet[2] == 0x05) {
721                         hci_drop_link_key_for_bd_addr(&addr);
722                     }
723                 }
724             }
725             break;
726 
727         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
728             handle = READ_BT_16(packet, 3);
729             conn = hci_connection_for_handle(handle);
730             if (!conn) break;
731             if (!packet[2]){
732                 uint8_t * features = &packet[5];
733                 if (features[6] & (1 << 3)){
734                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
735                 }
736             }
737             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
738             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
739             if (conn->bonding_flags & BONDING_DEDICATED){
740                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
741             }
742             break;
743 
744         case HCI_EVENT_LINK_KEY_REQUEST:
745             log_info("HCI_EVENT_LINK_KEY_REQUEST\n");
746             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
747             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
748             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
749             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
750             hci_run();
751             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
752             return;
753 
754         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
755             bt_flip_addr(addr, &packet[2]);
756             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
757             if (!conn) break;
758             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
759             link_key_type_t link_key_type = (link_key_type_t)packet[24];
760             // Change Connection Encryption keeps link key type
761             if (link_key_type != CHANGED_COMBINATION_KEY){
762                 conn->link_key_type = link_key_type;
763             }
764             if (!hci_stack->remote_device_db) break;
765             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
766             // still forward event to allow dismiss of pairing dialog
767             break;
768         }
769 
770         case HCI_EVENT_PIN_CODE_REQUEST:
771             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
772             // non-bondable mode: pin code negative reply will be sent
773             if (!hci_stack->bondable){
774                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
775                 hci_run();
776                 return;
777             }
778             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
779             if (!hci_stack->remote_device_db) break;
780             bt_flip_addr(addr, &packet[2]);
781             hci_stack->remote_device_db->delete_link_key(&addr);
782             break;
783 
784         case HCI_EVENT_IO_CAPABILITY_REQUEST:
785             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
786             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
787             break;
788 
789         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
790             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
791             if (!hci_stack->ssp_auto_accept) break;
792             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
793             break;
794 
795         case HCI_EVENT_USER_PASSKEY_REQUEST:
796             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
797             if (!hci_stack->ssp_auto_accept) break;
798             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
799             break;
800 
801         case HCI_EVENT_ENCRYPTION_CHANGE:
802             handle = READ_BT_16(packet, 3);
803             conn = hci_connection_for_handle(handle);
804             if (!conn) break;
805             if (packet[2] == 0) {
806                 if (packet[5]){
807                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
808                 } else {
809                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
810                 }
811             }
812             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
813             break;
814 
815         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
816             handle = READ_BT_16(packet, 3);
817             conn = hci_connection_for_handle(handle);
818             if (!conn) break;
819 
820             // dedicated bonding: send result and disconnect
821             if (conn->bonding_flags & BONDING_DEDICATED){
822                 conn->bonding_flags &= ~BONDING_DEDICATED;
823                 hci_emit_dedicated_bonding_result( conn, packet[2]);
824                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
825                 break;
826             }
827 
828             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
829                 // link key sufficient for requested security
830                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
831                 break;
832             }
833             // not enough
834             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
835             break;
836 
837 #ifndef EMBEDDED
838         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
839             if (!hci_stack->remote_device_db) break;
840             if (packet[2]) break; // status not ok
841             bt_flip_addr(addr, &packet[3]);
842             // fix for invalid remote names - terminate on 0xff
843             for (i=0; i<248;i++){
844                 if (packet[9+i] == 0xff){
845                     packet[9+i] = 0;
846                     break;
847                 }
848             }
849             memset(&device_name, 0, sizeof(device_name_t));
850             strncpy((char*) device_name, (char*) &packet[9], 248);
851             hci_stack->remote_device_db->put_name(&addr, &device_name);
852             break;
853 
854         case HCI_EVENT_INQUIRY_RESULT:
855         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
856             if (!hci_stack->remote_device_db) break;
857             // first send inq result packet
858             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
859             // then send cached remote names
860             for (i=0; i<packet[2];i++){
861                 bt_flip_addr(addr, &packet[3+i*6]);
862                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
863                     hci_emit_remote_name_cached(&addr, &device_name);
864                 }
865             }
866             return;
867 #endif
868 
869         case HCI_EVENT_DISCONNECTION_COMPLETE:
870             if (!packet[2]){
871                 handle = READ_BT_16(packet, 3);
872                 hci_connection_t * conn = hci_connection_for_handle(handle);
873                 if (conn) {
874                     hci_shutdown_connection(conn);
875                 }
876             }
877             break;
878 
879         case HCI_EVENT_HARDWARE_ERROR:
880             if(hci_stack->control && hci_stack->control->hw_error){
881                 (*hci_stack->control->hw_error)();
882             }
883             break;
884 
885         case DAEMON_EVENT_HCI_PACKET_SENT:
886             // free packet buffer for asynchronous transport
887             if (hci_transport_synchronous()) break;
888             hci_stack->hci_packet_buffer_reserved = 0;
889             break;
890 
891 #ifdef HAVE_BLE
892         case HCI_EVENT_LE_META:
893             switch (packet[2]){
894                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
895                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
896                     le_handle_advertisement_report(packet, size);
897                     break;
898                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
899                     // Connection management
900                     bt_flip_addr(addr, &packet[8]);
901                     addr_type = (bd_addr_type_t)packet[7];
902                     log_info("LE Connection_complete (status=%u) type %u, %s\n", packet[3], addr_type, bd_addr_to_str(addr));
903                     // LE connections are auto-accepted, so just create a connection if there isn't one already
904                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
905                     if (packet[3]){
906                         if (conn){
907                             // outgoing connection failed, remove entry
908                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
909                             btstack_memory_hci_connection_free( conn );
910 
911                         }
912                         // if authentication error, also delete link key
913                         if (packet[3] == 0x05) {
914                             hci_drop_link_key_for_bd_addr(&addr);
915                         }
916                         break;
917                     }
918                     if (!conn){
919                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
920                     }
921                     if (!conn){
922                         // no memory
923                         break;
924                     }
925 
926                     conn->state = OPEN;
927                     conn->con_handle = READ_BT_16(packet, 4);
928 
929                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
930 
931                     // restart timer
932                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
933                     // run_loop_add_timer(&conn->timeout);
934 
935                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
936 
937                     hci_emit_nr_connections_changed();
938                     break;
939 
940             // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]);
941 
942                 default:
943                     break;
944             }
945             break;
946 #endif
947 
948         default:
949             break;
950     }
951 
952     // handle BT initialization
953     if (hci_stack->state == HCI_STATE_INITIALIZING){
954         if (hci_stack->substate % 2){
955             // odd: waiting for event
956             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
957                 // wait for explicit COMMAND COMPLETE on RESET
958                 if (hci_stack->substate > 1 || COMMAND_COMPLETE_EVENT(packet, hci_reset)) {
959                     hci_stack->substate++;
960                 }
961             }
962         }
963     }
964 
965     // help with BT sleep
966     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
967         && hci_stack->substate == 1
968         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
969         hci_stack->substate++;
970     }
971 
972     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
973 
974 	// execute main loop
975 	hci_run();
976 }
977 
978 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
979     switch (packet_type) {
980         case HCI_EVENT_PACKET:
981             event_handler(packet, size);
982             break;
983         case HCI_ACL_DATA_PACKET:
984             acl_handler(packet, size);
985             break;
986         default:
987             break;
988     }
989 }
990 
991 /** Register HCI packet handlers */
992 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
993     hci_stack->packet_handler = handler;
994 }
995 
996 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
997 
998 #ifdef HAVE_MALLOC
999     if (!hci_stack) {
1000         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1001     }
1002 #else
1003     hci_stack = &hci_stack_static;
1004 #endif
1005     memset(hci_stack, 0, sizeof(hci_stack_t));
1006 
1007     // reference to use transport layer implementation
1008     hci_stack->hci_transport = transport;
1009 
1010     // references to used control implementation
1011     hci_stack->control = control;
1012 
1013     // reference to used config
1014     hci_stack->config = config;
1015 
1016     // no connections yet
1017     hci_stack->connections = NULL;
1018     hci_stack->discoverable = 0;
1019     hci_stack->connectable = 0;
1020     hci_stack->bondable = 1;
1021 
1022     // no pending cmds
1023     hci_stack->decline_reason = 0;
1024     hci_stack->new_scan_enable_value = 0xff;
1025 
1026     // higher level handler
1027     hci_stack->packet_handler = dummy_handler;
1028 
1029     // store and open remote device db
1030     hci_stack->remote_device_db = remote_device_db;
1031     if (hci_stack->remote_device_db) {
1032         hci_stack->remote_device_db->open();
1033     }
1034 
1035     // max acl payload size defined in config.h
1036     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1037 
1038     // register packet handlers with transport
1039     transport->register_packet_handler(&packet_handler);
1040 
1041     hci_stack->state = HCI_STATE_OFF;
1042 
1043     // class of device
1044     hci_stack->class_of_device = 0x007a020c; // Smartphone
1045 
1046     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1047     hci_stack->ssp_enable = 1;
1048     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1049     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1050     hci_stack->ssp_auto_accept = 1;
1051 
1052     // LE
1053     hci_stack->adv_addr_type = 0;
1054     memset(hci_stack->adv_address, 0, 6);
1055     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1056 }
1057 
1058 void hci_close(){
1059     // close remote device db
1060     if (hci_stack->remote_device_db) {
1061         hci_stack->remote_device_db->close();
1062     }
1063     while (hci_stack->connections) {
1064         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1065     }
1066     hci_power_control(HCI_POWER_OFF);
1067 
1068 #ifdef HAVE_MALLOC
1069     free(hci_stack);
1070 #endif
1071     hci_stack = NULL;
1072 }
1073 
1074 void hci_set_class_of_device(uint32_t class_of_device){
1075     hci_stack->class_of_device = class_of_device;
1076 }
1077 
1078 void hci_disable_l2cap_timeout_check(){
1079     disable_l2cap_timeouts = 1;
1080 }
1081 // State-Module-Driver overview
1082 // state                    module  low-level
1083 // HCI_STATE_OFF             off      close
1084 // HCI_STATE_INITIALIZING,   on       open
1085 // HCI_STATE_WORKING,        on       open
1086 // HCI_STATE_HALTING,        on       open
1087 // HCI_STATE_SLEEPING,    off/sleep   close
1088 // HCI_STATE_FALLING_ASLEEP  on       open
1089 
1090 static int hci_power_control_on(void){
1091 
1092     // power on
1093     int err = 0;
1094     if (hci_stack->control && hci_stack->control->on){
1095         err = (*hci_stack->control->on)(hci_stack->config);
1096     }
1097     if (err){
1098         log_error( "POWER_ON failed\n");
1099         hci_emit_hci_open_failed();
1100         return err;
1101     }
1102 
1103     // open low-level device
1104     err = hci_stack->hci_transport->open(hci_stack->config);
1105     if (err){
1106         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
1107         if (hci_stack->control && hci_stack->control->off){
1108             (*hci_stack->control->off)(hci_stack->config);
1109         }
1110         hci_emit_hci_open_failed();
1111         return err;
1112     }
1113     return 0;
1114 }
1115 
1116 static void hci_power_control_off(void){
1117 
1118     log_info("hci_power_control_off\n");
1119 
1120     // close low-level device
1121     hci_stack->hci_transport->close(hci_stack->config);
1122 
1123     log_info("hci_power_control_off - hci_transport closed\n");
1124 
1125     // power off
1126     if (hci_stack->control && hci_stack->control->off){
1127         (*hci_stack->control->off)(hci_stack->config);
1128     }
1129 
1130     log_info("hci_power_control_off - control closed\n");
1131 
1132     hci_stack->state = HCI_STATE_OFF;
1133 }
1134 
1135 static void hci_power_control_sleep(void){
1136 
1137     log_info("hci_power_control_sleep\n");
1138 
1139 #if 0
1140     // don't close serial port during sleep
1141 
1142     // close low-level device
1143     hci_stack->hci_transport->close(hci_stack->config);
1144 #endif
1145 
1146     // sleep mode
1147     if (hci_stack->control && hci_stack->control->sleep){
1148         (*hci_stack->control->sleep)(hci_stack->config);
1149     }
1150 
1151     hci_stack->state = HCI_STATE_SLEEPING;
1152 }
1153 
1154 static int hci_power_control_wake(void){
1155 
1156     log_info("hci_power_control_wake\n");
1157 
1158     // wake on
1159     if (hci_stack->control && hci_stack->control->wake){
1160         (*hci_stack->control->wake)(hci_stack->config);
1161     }
1162 
1163 #if 0
1164     // open low-level device
1165     int err = hci_stack->hci_transport->open(hci_stack->config);
1166     if (err){
1167         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
1168         if (hci_stack->control && hci_stack->control->off){
1169             (*hci_stack->control->off)(hci_stack->config);
1170         }
1171         hci_emit_hci_open_failed();
1172         return err;
1173     }
1174 #endif
1175 
1176     return 0;
1177 }
1178 
1179 
1180 int hci_power_control(HCI_POWER_MODE power_mode){
1181 
1182     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack->state);
1183 
1184     int err = 0;
1185     switch (hci_stack->state){
1186 
1187         case HCI_STATE_OFF:
1188             switch (power_mode){
1189                 case HCI_POWER_ON:
1190                     err = hci_power_control_on();
1191                     if (err) return err;
1192                     // set up state machine
1193                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1194                     hci_stack->state = HCI_STATE_INITIALIZING;
1195                     hci_stack->substate = 0;
1196                     break;
1197                 case HCI_POWER_OFF:
1198                     // do nothing
1199                     break;
1200                 case HCI_POWER_SLEEP:
1201                     // do nothing (with SLEEP == OFF)
1202                     break;
1203             }
1204             break;
1205 
1206         case HCI_STATE_INITIALIZING:
1207             switch (power_mode){
1208                 case HCI_POWER_ON:
1209                     // do nothing
1210                     break;
1211                 case HCI_POWER_OFF:
1212                     // no connections yet, just turn it off
1213                     hci_power_control_off();
1214                     break;
1215                 case HCI_POWER_SLEEP:
1216                     // no connections yet, just turn it off
1217                     hci_power_control_sleep();
1218                     break;
1219             }
1220             break;
1221 
1222         case HCI_STATE_WORKING:
1223             switch (power_mode){
1224                 case HCI_POWER_ON:
1225                     // do nothing
1226                     break;
1227                 case HCI_POWER_OFF:
1228                     // see hci_run
1229                     hci_stack->state = HCI_STATE_HALTING;
1230                     break;
1231                 case HCI_POWER_SLEEP:
1232                     // see hci_run
1233                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1234                     hci_stack->substate = 0;
1235                     break;
1236             }
1237             break;
1238 
1239         case HCI_STATE_HALTING:
1240             switch (power_mode){
1241                 case HCI_POWER_ON:
1242                     // set up state machine
1243                     hci_stack->state = HCI_STATE_INITIALIZING;
1244                     hci_stack->substate = 0;
1245                     break;
1246                 case HCI_POWER_OFF:
1247                     // do nothing
1248                     break;
1249                 case HCI_POWER_SLEEP:
1250                     // see hci_run
1251                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1252                     hci_stack->substate = 0;
1253                     break;
1254             }
1255             break;
1256 
1257         case HCI_STATE_FALLING_ASLEEP:
1258             switch (power_mode){
1259                 case HCI_POWER_ON:
1260 
1261 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1262                     // nothing to do, if H4 supports power management
1263                     if (bt_control_iphone_power_management_enabled()){
1264                         hci_stack->state = HCI_STATE_INITIALIZING;
1265                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1266                         break;
1267                     }
1268 #endif
1269                     // set up state machine
1270                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1271                     hci_stack->state = HCI_STATE_INITIALIZING;
1272                     hci_stack->substate = 0;
1273                     break;
1274                 case HCI_POWER_OFF:
1275                     // see hci_run
1276                     hci_stack->state = HCI_STATE_HALTING;
1277                     break;
1278                 case HCI_POWER_SLEEP:
1279                     // do nothing
1280                     break;
1281             }
1282             break;
1283 
1284         case HCI_STATE_SLEEPING:
1285             switch (power_mode){
1286                 case HCI_POWER_ON:
1287 
1288 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1289                     // nothing to do, if H4 supports power management
1290                     if (bt_control_iphone_power_management_enabled()){
1291                         hci_stack->state = HCI_STATE_INITIALIZING;
1292                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1293                         hci_update_scan_enable();
1294                         break;
1295                     }
1296 #endif
1297                     err = hci_power_control_wake();
1298                     if (err) return err;
1299                     // set up state machine
1300                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1301                     hci_stack->state = HCI_STATE_INITIALIZING;
1302                     hci_stack->substate = 0;
1303                     break;
1304                 case HCI_POWER_OFF:
1305                     hci_stack->state = HCI_STATE_HALTING;
1306                     break;
1307                 case HCI_POWER_SLEEP:
1308                     // do nothing
1309                     break;
1310             }
1311             break;
1312     }
1313 
1314     // create internal event
1315 	hci_emit_state();
1316 
1317 	// trigger next/first action
1318 	hci_run();
1319 
1320     return 0;
1321 }
1322 
1323 static void hci_update_scan_enable(void){
1324     // 2 = page scan, 1 = inq scan
1325     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1326     hci_run();
1327 }
1328 
1329 void hci_discoverable_control(uint8_t enable){
1330     if (enable) enable = 1; // normalize argument
1331 
1332     if (hci_stack->discoverable == enable){
1333         hci_emit_discoverable_enabled(hci_stack->discoverable);
1334         return;
1335     }
1336 
1337     hci_stack->discoverable = enable;
1338     hci_update_scan_enable();
1339 }
1340 
1341 void hci_connectable_control(uint8_t enable){
1342     if (enable) enable = 1; // normalize argument
1343 
1344     // don't emit event
1345     if (hci_stack->connectable == enable) return;
1346 
1347     hci_stack->connectable = enable;
1348     hci_update_scan_enable();
1349 }
1350 
1351 bd_addr_t * hci_local_bd_addr(void){
1352     return &hci_stack->local_bd_addr;
1353 }
1354 
1355 void hci_run(){
1356 
1357     hci_connection_t * connection;
1358     linked_item_t * it;
1359 
1360     if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return;
1361 
1362     // global/non-connection oriented commands
1363 
1364     // decline incoming connections
1365     if (hci_stack->decline_reason){
1366         uint8_t reason = hci_stack->decline_reason;
1367         hci_stack->decline_reason = 0;
1368         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1369         return;
1370     }
1371 
1372     // send scan enable
1373     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1374         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1375         hci_stack->new_scan_enable_value = 0xff;
1376         return;
1377     }
1378 
1379 #ifdef HAVE_BLE
1380     // handle le scan
1381     if (hci_stack->state == HCI_STATE_WORKING){
1382         switch(hci_stack->le_scanning_state){
1383             case LE_START_SCAN:
1384                 hci_stack->le_scanning_state = LE_SCANNING;
1385                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1386                 return;
1387 
1388             case LE_STOP_SCAN:
1389                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1390                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1391                 return;
1392             default:
1393                 break;
1394         }
1395     }
1396 #endif
1397 
1398     // send pending HCI commands
1399     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1400         connection = (hci_connection_t *) it;
1401 
1402         if (connection->state == SEND_DISCONNECT){
1403             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1404             connection->state = SENT_DISCONNECT;
1405             return;
1406         }
1407 
1408         if (connection->state == SEND_CREATE_CONNECTION){
1409             switch(connection->address_type){
1410                 case BD_ADDR_TYPE_CLASSIC:
1411                     log_info("sending hci_create_connection\n");
1412                     hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1413                     break;
1414                 default:
1415 #ifdef HAVE_BLE
1416                     log_info("sending hci_le_create_connection\n");
1417                     hci_send_cmd(&hci_le_create_connection,
1418                                  1000,      // scan interval: 625 ms
1419                                  1000,      // scan interval: 625 ms
1420                                  0,         // don't use whitelist
1421                                  connection->address_type, // peer address type
1422                                  connection->address,       // peer bd addr
1423                                  0,         // our addr type: public
1424                                  80,        // conn interval min
1425                                  80,        // conn interval max (3200 * 0.625)
1426                                  0,         // conn latency
1427                                  2000,      // supervision timeout
1428                                  0,         // min ce length
1429                                  1000       // max ce length
1430                                  );
1431 
1432                     connection->state = SENT_CREATE_CONNECTION;
1433 #endif
1434                     break;
1435             }
1436             return;
1437         }
1438 
1439         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1440             log_info("sending hci_accept_connection_request\n");
1441             connection->state = ACCEPTED_CONNECTION_REQUEST;
1442             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1443             return;
1444         }
1445 
1446         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1447             log_info("responding to link key request\n");
1448             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1449             link_key_t link_key;
1450             link_key_type_t link_key_type;
1451             if ( hci_stack->remote_device_db
1452               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1453               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1454                connection->link_key_type = link_key_type;
1455                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1456             } else {
1457                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1458             }
1459             return;
1460         }
1461 
1462         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1463             log_info("denying to pin request\n");
1464             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1465             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1466             return;
1467         }
1468 
1469         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1470             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1471             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1472             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1473                 // tweak authentication requirements
1474                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1475                 if (connection->bonding_flags & BONDING_DEDICATED){
1476                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1477                 }
1478                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1479                     authreq |= 1;
1480                 }
1481                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1482             } else {
1483                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1484             }
1485             return;
1486         }
1487 
1488         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1489             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1490             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1491             return;
1492         }
1493 
1494         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1495             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1496             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1497             return;
1498         }
1499 
1500         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1501             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1502             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1503             return;
1504         }
1505 
1506         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1507             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1508             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1509             return;
1510         }
1511         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1512             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1513             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1514             return;
1515         }
1516         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1517             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1518             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1519             return;
1520         }
1521         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1522             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1523             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1524             return;
1525         }
1526     }
1527 
1528     switch (hci_stack->state){
1529         case HCI_STATE_INITIALIZING:
1530             // log_info("hci_init: substate %u\n", hci_stack->substate);
1531             if (hci_stack->substate % 2) {
1532                 // odd: waiting for command completion
1533                 return;
1534             }
1535             switch (hci_stack->substate >> 1){
1536                 case 0: // RESET
1537                     hci_send_cmd(&hci_reset);
1538 
1539                     if (hci_stack->config == 0 || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
1540                         // skip baud change
1541                         hci_stack->substate = 4; // >> 1 = 2
1542                     }
1543                     break;
1544                 case 1: // SEND BAUD CHANGE
1545                     hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
1546                     hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1547                     break;
1548                 case 2: // LOCAL BAUD CHANGE
1549                     hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
1550                     hci_stack->substate += 2;
1551                     // break missing here for fall through
1552 
1553                 case 3:
1554                     // Custom initialization
1555                     if (hci_stack->control && hci_stack->control->next_cmd){
1556                         int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
1557                         if (valid_cmd){
1558                             int size = 3 + hci_stack->hci_packet_buffer[2];
1559                             hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1560                             hci_stack->substate = 4; // more init commands
1561                             break;
1562                         }
1563                         log_info("hci_run: init script done\n\r");
1564                     }
1565                     // otherwise continue
1566 					hci_send_cmd(&hci_read_bd_addr);
1567 					break;
1568 				case 4:
1569 					hci_send_cmd(&hci_read_buffer_size);
1570 					break;
1571                 case 5:
1572                     hci_send_cmd(&hci_read_local_supported_features);
1573                     break;
1574                 case 6:
1575                     if (hci_le_supported()){
1576                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1577                     } else {
1578                         // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1579                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1580                     }
1581 
1582                     // skip Classic init commands for LE only chipsets
1583                     if (!hci_classic_supported()){
1584                         if (hci_le_supported()){
1585                             hci_stack->substate = 11 << 1;    // skip all classic command
1586                         } else {
1587                             log_error("Neither BR/EDR nor LE supported");
1588                             hci_stack->substate = 13 << 1;    // skip all
1589                         }
1590                     }
1591                     break;
1592                 case 7:
1593                     if (hci_ssp_supported()){
1594                         hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1595                         break;
1596                     }
1597                     hci_stack->substate += 2;
1598                     // break missing here for fall through
1599 
1600                 case 8:
1601                     // ca. 15 sec
1602                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1603                     break;
1604                 case 9:
1605                     hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1606                     break;
1607                 case 10:
1608                     if (hci_stack->local_name){
1609                         hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
1610                     } else {
1611                         char hostname[30];
1612 #ifdef EMBEDDED
1613                         // BTstack-11:22:33:44:55:66
1614                         strcpy(hostname, "BTstack ");
1615                         strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
1616                         printf("---> Name %s\n", hostname);
1617 #else
1618                         // hostname for POSIX systems
1619                         gethostname(hostname, 30);
1620                         hostname[29] = '\0';
1621 #endif
1622                         hci_send_cmd(&hci_write_local_name, hostname);
1623                     }
1624                     break;
1625                 case 11:
1626 					hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1627                     if (!hci_le_supported()){
1628                         // SKIP LE init for Classic only configuration
1629                         hci_stack->substate = 13 << 1;
1630                     }
1631 					break;
1632 
1633 #ifdef HAVE_BLE
1634                 // LE INIT
1635                 case 12:
1636                     hci_send_cmd(&hci_le_read_buffer_size);
1637                     break;
1638                 case 13:
1639                     // LE Supported Host = 1, Simultaneous Host = 0
1640                     hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1641                     break;
1642 #endif
1643 
1644                 // DONE
1645                 case 14:
1646                     // done.
1647                     hci_stack->state = HCI_STATE_WORKING;
1648                     hci_emit_state();
1649                     break;
1650                 default:
1651                     break;
1652             }
1653             hci_stack->substate++;
1654             break;
1655 
1656         case HCI_STATE_HALTING:
1657 
1658             log_info("HCI_STATE_HALTING\n");
1659             // close all open connections
1660             connection =  (hci_connection_t *) hci_stack->connections;
1661             if (connection){
1662 
1663                 // send disconnect
1664                 if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return;
1665 
1666                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1667                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1668 
1669                 // send disconnected event right away - causes higher layer connections to get closed, too.
1670                 hci_shutdown_connection(connection);
1671                 return;
1672             }
1673             log_info("HCI_STATE_HALTING, calling off\n");
1674 
1675             // switch mode
1676             hci_power_control_off();
1677 
1678             log_info("HCI_STATE_HALTING, emitting state\n");
1679             hci_emit_state();
1680             log_info("HCI_STATE_HALTING, done\n");
1681             break;
1682 
1683         case HCI_STATE_FALLING_ASLEEP:
1684             switch(hci_stack->substate) {
1685                 case 0:
1686                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1687                     // close all open connections
1688                     connection =  (hci_connection_t *) hci_stack->connections;
1689 
1690 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1691                     // don't close connections, if H4 supports power management
1692                     if (bt_control_iphone_power_management_enabled()){
1693                         connection = NULL;
1694                     }
1695 #endif
1696                     if (connection){
1697 
1698                         // send disconnect
1699                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1700 
1701                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1702                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1703 
1704                         // send disconnected event right away - causes higher layer connections to get closed, too.
1705                         hci_shutdown_connection(connection);
1706                         return;
1707                     }
1708 
1709                     if (hci_classic_supported()){
1710                         // disable page and inquiry scan
1711                         if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return;
1712 
1713                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
1714                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
1715 
1716                         // continue in next sub state
1717                         hci_stack->substate++;
1718                         break;
1719                     }
1720                     // fall through for ble-only chips
1721 
1722                 case 2:
1723                     log_info("HCI_STATE_HALTING, calling sleep\n");
1724 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1725                     // don't actually go to sleep, if H4 supports power management
1726                     if (bt_control_iphone_power_management_enabled()){
1727                         // SLEEP MODE reached
1728                         hci_stack->state = HCI_STATE_SLEEPING;
1729                         hci_emit_state();
1730                         break;
1731                     }
1732 #endif
1733                     // switch mode
1734                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
1735                     hci_emit_state();
1736                     break;
1737 
1738                 default:
1739                     break;
1740             }
1741             break;
1742 
1743         default:
1744             break;
1745     }
1746 }
1747 
1748 int hci_send_cmd_packet(uint8_t *packet, int size){
1749     bd_addr_t addr;
1750     hci_connection_t * conn;
1751     // house-keeping
1752 
1753     // create_connection?
1754     if (IS_COMMAND(packet, hci_create_connection)){
1755         bt_flip_addr(addr, &packet[3]);
1756         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1757 
1758         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1759         if (!conn){
1760             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1761             if (!conn){
1762                 // notify client that alloc failed
1763                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1764                 return 0; // don't sent packet to controller
1765             }
1766             conn->state = SEND_CREATE_CONNECTION;
1767         }
1768         log_info("conn state %u", conn->state);
1769         switch (conn->state){
1770             // if connection active exists
1771             case OPEN:
1772                 // and OPEN, emit connection complete command, don't send to controller
1773                 hci_emit_connection_complete(conn, 0);
1774                 return 0;
1775             case SEND_CREATE_CONNECTION:
1776                 // connection created by hci, e.g. dedicated bonding
1777                 break;
1778             default:
1779                 // otherwise, just ignore as it is already in the open process
1780                 return 0;
1781         }
1782         conn->state = SENT_CREATE_CONNECTION;
1783     }
1784 
1785     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1786         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1787     }
1788     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1789         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1790     }
1791 
1792     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1793         if (hci_stack->remote_device_db){
1794             bt_flip_addr(addr, &packet[3]);
1795             hci_stack->remote_device_db->delete_link_key(&addr);
1796         }
1797     }
1798 
1799     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
1800     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
1801         bt_flip_addr(addr, &packet[3]);
1802         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1803         if (conn){
1804             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
1805         }
1806     }
1807 
1808     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
1809     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
1810     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
1811     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
1812         bt_flip_addr(addr, &packet[3]);
1813         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1814         if (conn){
1815             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
1816         }
1817     }
1818 
1819 #ifdef HAVE_BLE
1820     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
1821         hci_stack->adv_addr_type = packet[8];
1822     }
1823     if (IS_COMMAND(packet, hci_le_set_random_address)){
1824         bt_flip_addr(hci_stack->adv_address, &packet[3]);
1825     }
1826 #endif
1827 
1828     hci_stack->num_cmd_packets--;
1829     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1830 
1831     // free packet buffer for synchronous transport implementations
1832     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
1833         hci_stack->hci_packet_buffer_reserved = 0;
1834     }
1835 
1836     return err;
1837 }
1838 
1839 // disconnect because of security block
1840 void hci_disconnect_security_block(hci_con_handle_t con_handle){
1841     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1842     if (!connection) return;
1843     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
1844 }
1845 
1846 
1847 // Configure Secure Simple Pairing
1848 
1849 // enable will enable SSP during init
1850 void hci_ssp_set_enable(int enable){
1851     hci_stack->ssp_enable = enable;
1852 }
1853 
1854 int hci_local_ssp_activated(){
1855     return hci_ssp_supported() && hci_stack->ssp_enable;
1856 }
1857 
1858 // if set, BTstack will respond to io capability request using authentication requirement
1859 void hci_ssp_set_io_capability(int io_capability){
1860     hci_stack->ssp_io_capability = io_capability;
1861 }
1862 void hci_ssp_set_authentication_requirement(int authentication_requirement){
1863     hci_stack->ssp_authentication_requirement = authentication_requirement;
1864 }
1865 
1866 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1867 void hci_ssp_set_auto_accept(int auto_accept){
1868     hci_stack->ssp_auto_accept = auto_accept;
1869 }
1870 
1871 /**
1872  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1873  */
1874 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1875     va_list argptr;
1876     va_start(argptr, cmd);
1877     uint16_t size = hci_create_cmd_internal(hci_stack->hci_packet_buffer, cmd, argptr);
1878     va_end(argptr);
1879     return hci_send_cmd_packet(hci_stack->hci_packet_buffer, size);
1880 }
1881 
1882 // Create various non-HCI events.
1883 // TODO: generalize, use table similar to hci_create_command
1884 
1885 void hci_emit_state(){
1886     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
1887     uint8_t event[3];
1888     event[0] = BTSTACK_EVENT_STATE;
1889     event[1] = sizeof(event) - 2;
1890     event[2] = hci_stack->state;
1891     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1892     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1893 }
1894 
1895 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1896     uint8_t event[13];
1897     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1898     event[1] = sizeof(event) - 2;
1899     event[2] = status;
1900     bt_store_16(event, 3, conn->con_handle);
1901     bt_flip_addr(&event[5], conn->address);
1902     event[11] = 1; // ACL connection
1903     event[12] = 0; // encryption disabled
1904     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1905     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1906 }
1907 
1908 void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){
1909     uint8_t event[21];
1910     event[0] = HCI_EVENT_LE_META;
1911     event[1] = sizeof(event) - 2;
1912     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
1913     event[3] = status;
1914     bt_store_16(event, 4, conn->con_handle);
1915     event[6] = 0; // TODO: role
1916     event[7] = conn->address_type;
1917     bt_flip_addr(&event[8], conn->address);
1918     bt_store_16(event, 14, 0); // interval
1919     bt_store_16(event, 16, 0); // latency
1920     bt_store_16(event, 18, 0); // supervision timeout
1921     event[20] = 0; // master clock accuracy
1922     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1923     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1924 }
1925 
1926 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1927     uint8_t event[6];
1928     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1929     event[1] = sizeof(event) - 2;
1930     event[2] = 0; // status = OK
1931     bt_store_16(event, 3, handle);
1932     event[5] = reason;
1933     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1934     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1935 }
1936 
1937 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1938     if (disable_l2cap_timeouts) return;
1939     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1940     uint8_t event[4];
1941     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1942     event[1] = sizeof(event) - 2;
1943     bt_store_16(event, 2, conn->con_handle);
1944     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1945     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1946 }
1947 
1948 void hci_emit_nr_connections_changed(){
1949     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1950     uint8_t event[3];
1951     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1952     event[1] = sizeof(event) - 2;
1953     event[2] = nr_hci_connections();
1954     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1955     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1956 }
1957 
1958 void hci_emit_hci_open_failed(){
1959     log_info("BTSTACK_EVENT_POWERON_FAILED");
1960     uint8_t event[2];
1961     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1962     event[1] = sizeof(event) - 2;
1963     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1964     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1965 }
1966 
1967 #ifndef EMBEDDED
1968 void hci_emit_btstack_version() {
1969     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1970     uint8_t event[6];
1971     event[0] = BTSTACK_EVENT_VERSION;
1972     event[1] = sizeof(event) - 2;
1973     event[2] = BTSTACK_MAJOR;
1974     event[3] = BTSTACK_MINOR;
1975     bt_store_16(event, 4, BTSTACK_REVISION);
1976     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1977     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1978 }
1979 #endif
1980 
1981 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1982     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1983     uint8_t event[3];
1984     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1985     event[1] = sizeof(event) - 2;
1986     event[2] = enabled;
1987     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1988     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1989 }
1990 
1991 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1992     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1993     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1994     event[1] = sizeof(event) - 2 - 1;
1995     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1996     bt_flip_addr(&event[3], *addr);
1997     memcpy(&event[9], name, 248);
1998 
1999     event[9+248] = 0;   // assert \0 for log_info
2000     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2001 
2002     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2003     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2004 }
2005 
2006 void hci_emit_discoverable_enabled(uint8_t enabled){
2007     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2008     uint8_t event[3];
2009     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2010     event[1] = sizeof(event) - 2;
2011     event[2] = enabled;
2012     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2013     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2014 }
2015 
2016 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2017     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2018     uint8_t event[5];
2019     int pos = 0;
2020     event[pos++] = GAP_SECURITY_LEVEL;
2021     event[pos++] = sizeof(event) - 2;
2022     bt_store_16(event, 2, con_handle);
2023     pos += 2;
2024     event[pos++] = level;
2025     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2026     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2027 }
2028 
2029 void hci_emit_dedicated_bonding_result(hci_connection_t * connection, uint8_t status){
2030     log_info("hci_emit_dedicated_bonding_result %u ", status);
2031     uint8_t event[9];
2032     int pos = 0;
2033     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2034     event[pos++] = sizeof(event) - 2;
2035     event[pos++] = status;
2036     bt_flip_addr( * (bd_addr_t *) &event[pos], connection->address);
2037     pos += 6;
2038     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2039     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2040 }
2041 
2042 // query if remote side supports SSP
2043 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2044     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2045     if (!connection) return 0;
2046     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2047 }
2048 
2049 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2050     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2051 }
2052 
2053 // GAP API
2054 /**
2055  * @bbrief enable/disable bonding. default is enabled
2056  * @praram enabled
2057  */
2058 void gap_set_bondable_mode(int enable){
2059     hci_stack->bondable = enable ? 1 : 0;
2060 }
2061 
2062 /**
2063  * @brief map link keys to security levels
2064  */
2065 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2066     switch (link_key_type){
2067         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2068             return LEVEL_4;
2069         case COMBINATION_KEY:
2070         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2071             return LEVEL_3;
2072         default:
2073             return LEVEL_2;
2074     }
2075 }
2076 
2077 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2078     if (!connection) return LEVEL_0;
2079     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2080     return gap_security_level_for_link_key_type(connection->link_key_type);
2081 }
2082 
2083 
2084 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2085     printf("gap_mitm_protection_required_for_security_level %u\n", level);
2086     return level > LEVEL_2;
2087 }
2088 
2089 /**
2090  * @brief get current security level
2091  */
2092 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2093     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2094     if (!connection) return LEVEL_0;
2095     return gap_security_level_for_connection(connection);
2096 }
2097 
2098 /**
2099  * @brief request connection to device to
2100  * @result GAP_AUTHENTICATION_RESULT
2101  */
2102 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2103     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2104     if (!connection){
2105         hci_emit_security_level(con_handle, LEVEL_0);
2106         return;
2107     }
2108     gap_security_level_t current_level = gap_security_level(con_handle);
2109     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2110     if (current_level >= requested_level){
2111         hci_emit_security_level(con_handle, current_level);
2112         return;
2113     }
2114 
2115     connection->requested_security_level = requested_level;
2116 
2117     // would enabling ecnryption suffice (>= LEVEL_2)?
2118     if (hci_stack->remote_device_db){
2119         link_key_type_t link_key_type;
2120         link_key_t      link_key;
2121         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2122             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2123                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2124                 return;
2125             }
2126         }
2127     }
2128 
2129     // try to authenticate connection
2130     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2131     hci_run();
2132 }
2133 
2134 /**
2135  * @brief start dedicated bonding with device. disconnect after bonding
2136  * @param device
2137  * @param request MITM protection
2138  * @result GAP_DEDICATED_BONDING_COMPLETE
2139  */
2140 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2141 
2142     // create connection state machine
2143     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2144 
2145     if (!connection){
2146         return BTSTACK_MEMORY_ALLOC_FAILED;
2147     }
2148 
2149     // delete linkn key
2150     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2151 
2152     // configure LEVEL_2/3, dedicated bonding
2153     connection->state = SEND_CREATE_CONNECTION;
2154     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2155     printf("gap_dedicated_bonding, mitm %u -> level %u\n", mitm_protection_required, connection->requested_security_level);
2156     connection->bonding_flags = BONDING_DEDICATED;
2157 
2158     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2159 
2160     // handle: connnection failure (connection complete != ok)
2161     // handle: authentication failure
2162     // handle: disconnect on done
2163 
2164     hci_run();
2165 
2166     return 0;
2167 }
2168 
2169 void gap_set_local_name(const char * local_name){
2170     hci_stack->local_name = local_name;
2171 }
2172 
2173 le_command_status_t le_central_start_scan(){
2174     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2175     hci_stack->le_scanning_state = LE_START_SCAN;
2176     hci_run();
2177     return BLE_PERIPHERAL_OK;
2178 }
2179 
2180 le_command_status_t le_central_stop_scan(){
2181     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2182     hci_stack->le_scanning_state = LE_STOP_SCAN;
2183     hci_run();
2184     return BLE_PERIPHERAL_OK;
2185 }
2186 
2187 
2188 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2189     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2190     log_info("le_central_connect, conn struct %p", conn);
2191     if (!conn){
2192         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2193         if (!conn){
2194             // notify client that alloc failed
2195             hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2196             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2197         }
2198         conn->state = SEND_CREATE_CONNECTION;
2199         log_info("le_central_connect, state %u", conn->state);
2200         hci_run();
2201         return BLE_PERIPHERAL_OK;
2202     }
2203     log_info("le_central_connect, state %u", conn->state);
2204     hci_emit_le_connection_complete(conn, 0);
2205     hci_run();
2206     return BLE_PERIPHERAL_OK;
2207 }
2208 
2209 le_command_status_t le_central_connect_cancel(){
2210     // TODO implement
2211     return BLE_PERIPHERAL_OK;
2212 }
2213 
2214 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2215     hci_connection_t * conn = hci_connection_for_handle(handle);
2216     if (!conn){
2217         hci_emit_le_connection_complete(conn, 0);
2218         return BLE_PERIPHERAL_OK;
2219     }
2220     conn->state = SEND_DISCONNECT;
2221     hci_run();
2222     return BLE_PERIPHERAL_OK;
2223 }
2224