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