xref: /btstack/src/hci.c (revision f456b2d087a6e1ddbe99a3e330c53dac61037d12)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
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 BLUEKITCHEN GMBH 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
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  hci.c
40  *
41  *  Created by Matthias Ringwald on 4/29/09.
42  *
43  */
44 
45 #include "btstack-config.h"
46 
47 #include "hci.h"
48 #include "gap.h"
49 
50 #include <stdarg.h>
51 #include <string.h>
52 #include <stdio.h>
53 
54 #ifndef EMBEDDED
55 #ifdef _WIN32
56 #include "Winsock2.h"
57 #else
58 #include <unistd.h> // gethostbyname
59 #endif
60 #include <btstack/version.h>
61 #endif
62 
63 #include "btstack_memory.h"
64 #include "debug.h"
65 #include "hci_dump.h"
66 
67 #include <btstack/linked_list.h>
68 #include <btstack/hci_cmds.h>
69 
70 #define HCI_CONNECTION_TIMEOUT_MS 10000
71 
72 #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
73 
74 #ifdef USE_BLUETOOL
75 #include "../platforms/ios/src/bt_control_iphone.h"
76 #endif
77 
78 static void hci_update_scan_enable(void);
79 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
80 static void hci_connection_timeout_handler(timer_source_t *timer);
81 static void hci_connection_timestamp(hci_connection_t *connection);
82 static int  hci_power_control_on(void);
83 static void hci_power_control_off(void);
84 static void hci_state_reset();
85 
86 // the STACK is here
87 #ifndef HAVE_MALLOC
88 static hci_stack_t   hci_stack_static;
89 #endif
90 static hci_stack_t * hci_stack = NULL;
91 
92 // test helper
93 static uint8_t disable_l2cap_timeouts = 0;
94 
95 /**
96  * create connection for given address
97  *
98  * @return connection OR NULL, if no memory left
99  */
100 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
101     log_info("create_connection_for_addr %s", bd_addr_to_str(addr));
102     hci_connection_t * conn = btstack_memory_hci_connection_get();
103     if (!conn) return NULL;
104     BD_ADDR_COPY(conn->address, addr);
105     conn->address_type = addr_type;
106     conn->con_handle = 0xffff;
107     conn->authentication_flags = AUTH_FLAGS_NONE;
108     conn->bonding_flags = 0;
109     conn->requested_security_level = LEVEL_0;
110     linked_item_set_user(&conn->timeout.item, conn);
111     conn->timeout.process = hci_connection_timeout_handler;
112     hci_connection_timestamp(conn);
113     conn->acl_recombination_length = 0;
114     conn->acl_recombination_pos = 0;
115     conn->num_acl_packets_sent = 0;
116     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
117     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
118     return conn;
119 }
120 
121 
122 /**
123  * get le connection parameter range
124 *
125  * @return le connection parameter range struct
126  */
127 le_connection_parameter_range_t gap_le_get_connection_parameter_range(){
128     return hci_stack->le_connection_parameter_range;
129 }
130 
131 /**
132  * set le connection parameter range
133  *
134  */
135 
136 void gap_le_set_connection_parameter_range(le_connection_parameter_range_t range){
137     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_interval_min;
138     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_interval_max;
139     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_latency_min;
140     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_latency_max;
141     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = range.le_supervision_timeout_min;
142     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = range.le_supervision_timeout_max;
143 }
144 
145 /**
146  * get hci connections iterator
147  *
148  * @return hci connections iterator
149  */
150 
151 void hci_connections_get_iterator(linked_list_iterator_t *it){
152     linked_list_iterator_init(it, &hci_stack->connections);
153 }
154 
155 /**
156  * get connection for a given handle
157  *
158  * @return connection OR NULL, if not found
159  */
160 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
161     linked_list_iterator_t it;
162     linked_list_iterator_init(&it, &hci_stack->connections);
163     while (linked_list_iterator_has_next(&it)){
164         hci_connection_t * item = (hci_connection_t *) linked_list_iterator_next(&it);
165         if ( item->con_handle == con_handle ) {
166             return item;
167         }
168     }
169     return NULL;
170 }
171 
172 /**
173  * get connection for given address
174  *
175  * @return connection OR NULL, if not found
176  */
177 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
178     linked_list_iterator_t it;
179     linked_list_iterator_init(&it, &hci_stack->connections);
180     while (linked_list_iterator_has_next(&it)){
181         hci_connection_t * connection = (hci_connection_t *) linked_list_iterator_next(&it);
182         if (connection->address_type != addr_type)  continue;
183         if (memcmp(addr, connection->address, 6) != 0) continue;
184         return connection;
185     }
186     return NULL;
187 }
188 
189 static void hci_connection_timeout_handler(timer_source_t *timer){
190     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
191 #ifdef HAVE_TIME
192     struct timeval tv;
193     gettimeofday(&tv, NULL);
194     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
195         // connections might be timed out
196         hci_emit_l2cap_check_timeout(connection);
197     }
198 #endif
199 #ifdef HAVE_TICK
200     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
201         // connections might be timed out
202         hci_emit_l2cap_check_timeout(connection);
203     }
204 #endif
205     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
206     run_loop_add_timer(timer);
207 }
208 
209 static void hci_connection_timestamp(hci_connection_t *connection){
210 #ifdef HAVE_TIME
211     gettimeofday(&connection->timestamp, NULL);
212 #endif
213 #ifdef HAVE_TICK
214     connection->timestamp = embedded_get_ticks();
215 #endif
216 }
217 
218 
219 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
220     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
221 }
222 
223 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
224     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
225 }
226 
227 
228 /**
229  * add authentication flags and reset timer
230  * @note: assumes classic connection
231  */
232 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
233     bd_addr_t addr;
234     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
235     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
236     if (conn) {
237         connectionSetAuthenticationFlags(conn, flags);
238         hci_connection_timestamp(conn);
239     }
240 }
241 
242 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
243     hci_connection_t * conn = hci_connection_for_handle(handle);
244     if (!conn) return 0;
245     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
246     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
247     return 0;
248 }
249 
250 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
251     if (hci_stack->remote_device_db) {
252         hci_stack->remote_device_db->delete_link_key(addr);
253     }
254 }
255 
256 int hci_is_le_connection(hci_connection_t * connection){
257     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
258     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
259 }
260 
261 
262 /**
263  * count connections
264  */
265 static int nr_hci_connections(void){
266     int count = 0;
267     linked_item_t *it;
268     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
269     return count;
270 }
271 
272 /**
273  * Dummy handler called by HCI
274  */
275 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
276 }
277 
278 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
279     hci_connection_t * connection = hci_connection_for_handle(handle);
280     if (!connection) {
281         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
282         return 0;
283     }
284     return connection->num_acl_packets_sent;
285 }
286 
287 uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
288 
289     int num_packets_sent_classic = 0;
290     int num_packets_sent_le = 0;
291 
292     bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN;
293 
294     linked_item_t *it;
295     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
296         hci_connection_t * connection = (hci_connection_t *) it;
297         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
298             num_packets_sent_classic += connection->num_acl_packets_sent;
299         } else {
300             num_packets_sent_le += connection->num_acl_packets_sent;
301         }
302         // ignore connections that are not open, e.g., in state RECEIVED_DISCONNECTION_COMPLETE
303         if (connection->con_handle == con_handle && connection->state == OPEN){
304             address_type = connection->address_type;
305         }
306     }
307 
308     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
309     int free_slots_le = 0;
310 
311     if (free_slots_classic < 0){
312         log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num);
313         return 0;
314     }
315 
316     if (hci_stack->le_acl_packets_total_num){
317         // if we have LE slots, they are used
318         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
319         if (free_slots_le < 0){
320             log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num);
321             return 0;
322         }
323     } else {
324         // otherwise, classic slots are used for LE, too
325         free_slots_classic -= num_packets_sent_le;
326         if (free_slots_classic < 0){
327             log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num);
328             return 0;
329         }
330     }
331 
332     switch (address_type){
333         case BD_ADDR_TYPE_UNKNOWN:
334             log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
335             return 0;
336 
337         case BD_ADDR_TYPE_CLASSIC:
338             return free_slots_classic;
339 
340         default:
341            if (hci_stack->le_acl_packets_total_num){
342                return free_slots_le;
343            }
344            return free_slots_classic;
345     }
346 }
347 
348 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
349 int hci_can_send_command_packet_now(void){
350     if (hci_stack->hci_packet_buffer_reserved) return 0;
351 
352     // check for async hci transport implementations
353     if (hci_stack->hci_transport->can_send_packet_now){
354         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
355             return 0;
356         }
357     }
358 
359     return hci_stack->num_cmd_packets > 0;
360 }
361 
362 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
363     // check for async hci transport implementations
364     if (hci_stack->hci_transport->can_send_packet_now){
365         if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){
366             return 0;
367         }
368     }
369     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
370 }
371 
372 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
373     if (hci_stack->hci_packet_buffer_reserved) return 0;
374     return hci_can_send_prepared_acl_packet_now(con_handle);
375 }
376 
377 // used for internal checks in l2cap[-le].c
378 int hci_is_packet_buffer_reserved(void){
379     return hci_stack->hci_packet_buffer_reserved;
380 }
381 
382 // reserves outgoing packet buffer. @returns 1 if successful
383 int hci_reserve_packet_buffer(void){
384     if (hci_stack->hci_packet_buffer_reserved) {
385         log_error("hci_reserve_packet_buffer called but buffer already reserved");
386         return 0;
387     }
388     hci_stack->hci_packet_buffer_reserved = 1;
389     return 1;
390 }
391 
392 void hci_release_packet_buffer(void){
393     hci_stack->hci_packet_buffer_reserved = 0;
394 }
395 
396 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
397 int hci_transport_synchronous(void){
398     return hci_stack->hci_transport->can_send_packet_now == NULL;
399 }
400 
401 uint16_t hci_max_acl_le_data_packet_length(void){
402     return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length;
403 }
404 
405 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
406 
407     // log_info("hci_send_acl_packet_fragments  %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle);
408 
409     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
410     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
411     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
412         max_acl_data_packet_length = hci_stack->le_data_packets_length;
413     }
414 
415     // testing: reduce buffer to minimum
416     // max_acl_data_packet_length = 52;
417 
418     int err;
419     // multiple packets could be send on a synchronous HCI transport
420     while (1){
421 
422         // get current data
423         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
424         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
425         int more_fragments = 0;
426 
427         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
428         if (current_acl_data_packet_length > max_acl_data_packet_length){
429             more_fragments = 1;
430             current_acl_data_packet_length = max_acl_data_packet_length;
431         }
432 
433         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
434         if (acl_header_pos > 0){
435             uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0);
436             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
437             bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
438         }
439 
440         // update header len
441         bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
442 
443         // count packet
444         connection->num_acl_packets_sent++;
445 
446         // send packet
447         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
448         const int size = current_acl_data_packet_length + 4;
449         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
450         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
451 
452         // done yet?
453         if (!more_fragments) break;
454 
455         // update start of next fragment to send
456         hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
457 
458         // can send more?
459         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
460     }
461 
462     // done
463     hci_stack->acl_fragmentation_pos = 0;
464     hci_stack->acl_fragmentation_total_size = 0;
465 
466     // release buffer now for synchronous transport
467     if (hci_transport_synchronous()){
468         hci_release_packet_buffer();
469     }
470 
471     return err;
472 }
473 
474 // pre: caller has reserved the packet buffer
475 int hci_send_acl_packet_buffer(int size){
476 
477     // log_info("hci_send_acl_packet_buffer size %u", size);
478 
479     if (!hci_stack->hci_packet_buffer_reserved) {
480         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
481         return 0;
482     }
483 
484     uint8_t * packet = hci_stack->hci_packet_buffer;
485     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
486 
487     // check for free places on Bluetooth module
488     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
489         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
490         hci_release_packet_buffer();
491         return BTSTACK_ACL_BUFFERS_FULL;
492     }
493 
494     hci_connection_t *connection = hci_connection_for_handle( con_handle);
495     if (!connection) {
496         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
497         hci_release_packet_buffer();
498         return 0;
499     }
500     hci_connection_timestamp(connection);
501 
502     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
503 
504     // setup data
505     hci_stack->acl_fragmentation_total_size = size;
506     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
507 
508     return hci_send_acl_packet_fragments(connection);
509 }
510 
511 static void acl_handler(uint8_t *packet, int size){
512 
513     // log_info("acl_handler: size %u", size);
514 
515     // get info
516     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
517     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
518     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
519     uint16_t acl_length         = READ_ACL_LENGTH(packet);
520 
521     // ignore non-registered handle
522     if (!conn){
523         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
524         return;
525     }
526 
527     // assert packet is complete
528     if (acl_length + 4 != size){
529         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
530         return;
531     }
532 
533     // update idle timestamp
534     hci_connection_timestamp(conn);
535 
536     // handle different packet types
537     switch (acl_flags & 0x03) {
538 
539         case 0x01: // continuation fragment
540 
541             // sanity checks
542             if (conn->acl_recombination_pos == 0) {
543                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
544                 return;
545             }
546             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
547                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
548                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
549                 conn->acl_recombination_pos = 0;
550                 return;
551             }
552 
553             // append fragment payload (header already stored)
554             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
555             conn->acl_recombination_pos += acl_length;
556 
557             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
558             //        conn->acl_recombination_pos, conn->acl_recombination_length);
559 
560             // forward complete L2CAP packet if complete.
561             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
562 
563                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, &conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
564                 // reset recombination buffer
565                 conn->acl_recombination_length = 0;
566                 conn->acl_recombination_pos = 0;
567             }
568             break;
569 
570         case 0x02: { // first fragment
571 
572             // sanity check
573             if (conn->acl_recombination_pos) {
574                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
575                 conn->acl_recombination_pos = 0;
576             }
577 
578             // peek into L2CAP packet!
579             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
580 
581             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
582 
583             // compare fragment size to L2CAP packet size
584             if (acl_length >= l2cap_length + 4){
585 
586                 // forward fragment as L2CAP packet
587                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
588 
589             } else {
590 
591                 if (acl_length > HCI_ACL_BUFFER_SIZE){
592                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
593                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
594                     return;
595                 }
596 
597                 // store first fragment and tweak acl length for complete package
598                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
599                 conn->acl_recombination_pos    = acl_length + 4;
600                 conn->acl_recombination_length = l2cap_length;
601                 bt_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
602             }
603             break;
604 
605         }
606         default:
607             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
608             return;
609     }
610 
611     // execute main loop
612     hci_run();
613 }
614 
615 static void hci_shutdown_connection(hci_connection_t *conn){
616     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
617 
618     run_loop_remove_timer(&conn->timeout);
619 
620     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
621     btstack_memory_hci_connection_free( conn );
622 
623     // now it's gone
624     hci_emit_nr_connections_changed();
625 }
626 
627 static const uint16_t packet_type_sizes[] = {
628     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
629     HCI_ACL_DH1_SIZE, 0, 0, 0,
630     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
631     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
632 };
633 static const uint8_t  packet_type_feature_requirement_bit[] = {
634      0, // 3 slot packets
635      1, // 5 slot packets
636     25, // EDR 2 mpbs
637     26, // EDR 3 mbps
638     39, // 3 slot EDR packts
639     40, // 5 slot EDR packet
640 };
641 static const uint16_t packet_type_feature_packet_mask[] = {
642     0x0f00, // 3 slot packets
643     0xf000, // 5 slot packets
644     0x1102, // EDR 2 mpbs
645     0x2204, // EDR 3 mbps
646     0x0300, // 3 slot EDR packts
647     0x3000, // 5 slot EDR packet
648 };
649 
650 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
651     // enable packet types based on size
652     uint16_t packet_types = 0;
653     unsigned int i;
654     for (i=0;i<16;i++){
655         if (packet_type_sizes[i] == 0) continue;
656         if (packet_type_sizes[i] <= buffer_size){
657             packet_types |= 1 << i;
658         }
659     }
660     // disable packet types due to missing local supported features
661     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
662         int bit_idx = packet_type_feature_requirement_bit[i];
663         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
664         if (feature_set) continue;
665         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
666         packet_types &= ~packet_type_feature_packet_mask[i];
667     }
668     // flip bits for "may not be used"
669     packet_types ^= 0x3306;
670     return packet_types;
671 }
672 
673 uint16_t hci_usable_acl_packet_types(void){
674     return hci_stack->packet_types;
675 }
676 
677 uint8_t* hci_get_outgoing_packet_buffer(void){
678     // hci packet buffer is >= acl data packet length
679     return hci_stack->hci_packet_buffer;
680 }
681 
682 uint16_t hci_max_acl_data_packet_length(void){
683     return hci_stack->acl_data_packet_length;
684 }
685 
686 int hci_non_flushable_packet_boundary_flag_supported(void){
687     // No. 54, byte 6, bit 6
688     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
689 }
690 
691 int hci_ssp_supported(void){
692     // No. 51, byte 6, bit 3
693     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
694 }
695 
696 int hci_classic_supported(void){
697     // No. 37, byte 4, bit 5, = No BR/EDR Support
698     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
699 }
700 
701 int hci_le_supported(void){
702 #ifdef HAVE_BLE
703     // No. 37, byte 4, bit 6 = LE Supported (Controller)
704     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
705 #else
706     return 0;
707 #endif
708 }
709 
710 // get addr type and address used in advertisement packets
711 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
712     *addr_type = hci_stack->adv_addr_type;
713     if (hci_stack->adv_addr_type){
714         memcpy(addr, hci_stack->adv_address, 6);
715     } else {
716         memcpy(addr, hci_stack->local_bd_addr, 6);
717     }
718 }
719 
720 #ifdef HAVE_BLE
721 void le_handle_advertisement_report(uint8_t *packet, int size){
722     int offset = 3;
723     int num_reports = packet[offset];
724     offset += 1;
725 
726     int i;
727     log_info("HCI: handle adv report with num reports: %d", num_reports);
728     uint8_t event[2 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
729     for (i=0; i<num_reports;i++){
730         uint8_t data_length = packet[offset + 8];
731         uint8_t event_size = 10 + data_length;
732         int pos = 0;
733         event[pos++] = GAP_LE_ADVERTISING_REPORT;
734         event[pos++] = event_size;
735         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
736         offset += 8;
737         pos += 8;
738         event[pos++] = packet[offset + 1 + data_length]; // rssi
739         event[pos++] = packet[offset++]; //data_length;
740         memcpy(&event[pos], &packet[offset], data_length);
741         pos += data_length;
742         offset += data_length + 1; // rssi
743         hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
744         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
745     }
746 }
747 #endif
748 
749 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
750     uint8_t command_completed = 0;
751     if ((hci_stack->substate % 2) == 0) return;
752     // odd: waiting for event
753     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
754         uint16_t opcode = READ_BT_16(packet,3);
755         if (opcode == hci_stack->last_cmd_opcode){
756             command_completed = 1;
757             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate >> 1);
758         } else {
759             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
760         }
761     }
762     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
763         uint8_t  status = packet[2];
764         uint16_t opcode = READ_BT_16(packet,4);
765         if (opcode == hci_stack->last_cmd_opcode){
766             if (status){
767                 command_completed = 1;
768                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate >> 1);
769             } else {
770                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
771             }
772         } else {
773             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
774         }
775     }
776 
777     if (!command_completed) return;
778 
779     switch(hci_stack->substate >> 1){
780         default:
781             hci_stack->substate++;
782             break;
783     }
784 }
785 
786 static void hci_initializing_state_machine(){
787     if (hci_stack->substate % 2) {
788         // odd: waiting for command completion
789         return;
790     }
791     // log_info("hci_init: substate %u", hci_stack->substate >> 1);
792     switch (hci_stack->substate >> 1){
793         case 0: // RESET
794             hci_state_reset();
795 
796             hci_send_cmd(&hci_reset);
797             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
798                 // skip baud change
799                 hci_stack->substate = 2 << 1;
800             }
801             break;
802         case 1: // SEND BAUD CHANGE
803             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
804             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
805             hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
806             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
807             break;
808         case 2: // LOCAL BAUD CHANGE
809             log_info("Local baud rate change");
810             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
811             hci_stack->substate += 2;
812             // break missing here for fall through
813 
814         case 3: // SET BD ADDR
815             if ( hci_stack->custom_bd_addr_set && hci_stack->control && hci_stack->control->set_bd_addr_cmd){
816                 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
817                 hci_stack->control->set_bd_addr_cmd(hci_stack->config, hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
818                 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
819                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
820                 break;
821             }
822             hci_stack->substate += 2;
823             // break missing here for fall through
824 
825         case 4:
826             log_info("Custom init");
827             // Custom initialization
828             if (hci_stack->control && hci_stack->control->next_cmd){
829                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
830                 if (valid_cmd){
831                     int size = 3 + hci_stack->hci_packet_buffer[2];
832                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
833                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
834                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
835                     hci_stack->substate = 3 << 1; // more init commands
836                     break;
837                 }
838                 log_info("hci_run: init script done");
839             }
840             // otherwise continue
841             hci_send_cmd(&hci_read_bd_addr);
842             break;
843         case 5:
844             hci_send_cmd(&hci_read_buffer_size);
845             break;
846         case 6:
847             hci_send_cmd(&hci_read_local_supported_features);
848             break;
849         case 7:
850             if (hci_le_supported()){
851                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
852             } else {
853                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
854                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
855             }
856 
857             // skip Classic init commands for LE only chipsets
858             if (!hci_classic_supported()){
859                 if (hci_le_supported()){
860                     hci_stack->substate = 12 << 1;    // skip all classic command
861                 } else {
862                     log_error("Neither BR/EDR nor LE supported");
863                     hci_stack->substate = 15 << 1;    // skip all
864                 }
865             }
866             break;
867         case 8:
868             if (hci_ssp_supported()){
869                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
870                 break;
871             }
872             hci_stack->substate += 2;
873             // break missing here for fall through
874 
875         case 9:
876             // ca. 15 sec
877             hci_send_cmd(&hci_write_page_timeout, 0x6000);
878             break;
879         case 10:
880             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
881             break;
882         case 11:
883             if (hci_stack->local_name){
884                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
885             } else {
886                 char hostname[30];
887 #ifdef EMBEDDED
888                 // BTstack-11:22:33:44:55:66
889                 strcpy(hostname, "BTstack ");
890                 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
891                 log_info("---> Name %s", hostname);
892 #else
893                 // hostname for POSIX systems
894                 gethostname(hostname, 30);
895                 hostname[29] = '\0';
896 #endif
897                 hci_send_cmd(&hci_write_local_name, hostname);
898             }
899             break;
900         case 12:
901             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
902             if (!hci_le_supported()){
903                 // SKIP LE init for Classic only configuration
904                 hci_stack->substate = 15 << 1;
905             }
906             break;
907 
908 #ifdef HAVE_BLE
909         // LE INIT
910         case 13:
911             hci_send_cmd(&hci_le_read_buffer_size);
912             break;
913         case 14:
914             // LE Supported Host = 1, Simultaneous Host = 0
915             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
916             break;
917         case 15:
918             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
919             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
920             break;
921 #endif
922 
923         // DONE
924         case 16:
925             // done.
926             hci_stack->state = HCI_STATE_WORKING;
927             hci_emit_state();
928             break;
929         default:
930             break;
931     }
932     hci_stack->substate++;
933 }
934 
935 // avoid huge local variables
936 #ifndef EMBEDDED
937 static device_name_t device_name;
938 #endif
939 static void event_handler(uint8_t *packet, int size){
940 
941     uint16_t event_length = packet[1];
942 
943     // assert packet is complete
944     if (size != event_length + 2){
945         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
946         return;
947     }
948 
949     bd_addr_t addr;
950     bd_addr_type_t addr_type;
951     uint8_t link_type;
952     hci_con_handle_t handle;
953     hci_connection_t * conn;
954     int i;
955 
956     // log_info("HCI:EVENT:%02x", packet[0]);
957 
958     switch (packet[0]) {
959 
960         case HCI_EVENT_COMMAND_COMPLETE:
961             // get num cmd packets
962             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
963             hci_stack->num_cmd_packets = packet[2];
964 
965             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
966                 // from offset 5
967                 // status
968                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
969                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
970                 // ignore: SCO data packet len (8)
971                 hci_stack->acl_packets_total_num  = packet[9];
972                 // ignore: total num SCO packets
973                 if (hci_stack->state == HCI_STATE_INITIALIZING){
974                     // determine usable ACL payload size
975                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
976                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
977                     }
978                     log_info("hci_read_buffer_size: used size %u, count %u",
979                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num);
980                 }
981             }
982 #ifdef HAVE_BLE
983             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
984                 hci_stack->le_data_packets_length = READ_BT_16(packet, 6);
985                 hci_stack->le_acl_packets_total_num  = packet[8];
986                     // determine usable ACL payload size
987                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
988                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
989                     }
990                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
991             }
992 #endif
993             // Dump local address
994             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
995                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
996                 log_info("Local Address, Status: 0x%02x: Addr: %s",
997                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
998             }
999             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1000                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1001             }
1002             // Note: HCI init checks
1003             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
1004                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1005                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
1006                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
1007                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
1008                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
1009                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
1010 
1011                 // determine usable ACL packet types based on host buffer size and supported features
1012                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1013                 log_info("packet types %04x", hci_stack->packet_types);
1014 
1015                 // Classic/LE
1016                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1017             }
1018             break;
1019 
1020         case HCI_EVENT_COMMAND_STATUS:
1021             // get num cmd packets
1022             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
1023             hci_stack->num_cmd_packets = packet[3];
1024             break;
1025 
1026         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1027             int offset = 3;
1028             for (i=0; i<packet[2];i++){
1029                 handle = READ_BT_16(packet, offset);
1030                 offset += 2;
1031                 uint16_t num_packets = READ_BT_16(packet, offset);
1032                 offset += 2;
1033 
1034                 conn = hci_connection_for_handle(handle);
1035                 if (!conn){
1036                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1037                     continue;
1038                 }
1039 
1040                 if (conn->num_acl_packets_sent >= num_packets){
1041                     conn->num_acl_packets_sent -= num_packets;
1042                 } else {
1043                     log_error("hci_number_completed_packets, more slots freed then sent.");
1044                     conn->num_acl_packets_sent = 0;
1045                 }
1046                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1047             }
1048             break;
1049         }
1050         case HCI_EVENT_CONNECTION_REQUEST:
1051             bt_flip_addr(addr, &packet[2]);
1052             // TODO: eval COD 8-10
1053             link_type = packet[11];
1054             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1055             if (link_type == 1) { // ACL
1056                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1057                 if (!conn) {
1058                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1059                 }
1060                 if (!conn) {
1061                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1062                     hci_stack->decline_reason = 0x0d;
1063                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
1064                     break;
1065                 }
1066                 conn->state = RECEIVED_CONNECTION_REQUEST;
1067                 hci_run();
1068             } else {
1069                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
1070                 hci_stack->decline_reason = 0x0a;
1071                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
1072             }
1073             break;
1074 
1075         case HCI_EVENT_CONNECTION_COMPLETE:
1076             // Connection management
1077             bt_flip_addr(addr, &packet[5]);
1078             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1079             addr_type = BD_ADDR_TYPE_CLASSIC;
1080             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1081             if (conn) {
1082                 if (!packet[2]){
1083                     conn->state = OPEN;
1084                     conn->con_handle = READ_BT_16(packet, 3);
1085                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1086 
1087                     // restart timer
1088                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1089                     run_loop_add_timer(&conn->timeout);
1090 
1091                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1092 
1093                     hci_emit_nr_connections_changed();
1094                 } else {
1095                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1096                     uint8_t status = packet[2];
1097                     bd_addr_t bd_address;
1098                     memcpy(&bd_address, conn->address, 6);
1099 
1100                     // connection failed, remove entry
1101                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1102                     btstack_memory_hci_connection_free( conn );
1103 
1104                     // notify client if dedicated bonding
1105                     if (notify_dedicated_bonding_failed){
1106                         log_info("hci notify_dedicated_bonding_failed");
1107                         hci_emit_dedicated_bonding_result(bd_address, status);
1108                     }
1109 
1110                     // if authentication error, also delete link key
1111                     if (packet[2] == 0x05) {
1112                         hci_drop_link_key_for_bd_addr(&addr);
1113                     }
1114                 }
1115             }
1116             break;
1117 
1118         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1119             handle = READ_BT_16(packet, 3);
1120             conn = hci_connection_for_handle(handle);
1121             if (!conn) break;
1122             if (!packet[2]){
1123                 uint8_t * features = &packet[5];
1124                 if (features[6] & (1 << 3)){
1125                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1126                 }
1127             }
1128             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1129             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1130             if (conn->bonding_flags & BONDING_DEDICATED){
1131                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1132             }
1133             break;
1134 
1135         case HCI_EVENT_LINK_KEY_REQUEST:
1136             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1137             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1138             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1139             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
1140             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1141             hci_run();
1142             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1143             return;
1144 
1145         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1146             bt_flip_addr(addr, &packet[2]);
1147             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1148             if (!conn) break;
1149             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1150             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1151             // Change Connection Encryption keeps link key type
1152             if (link_key_type != CHANGED_COMBINATION_KEY){
1153                 conn->link_key_type = link_key_type;
1154             }
1155             if (!hci_stack->remote_device_db) break;
1156             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
1157             // still forward event to allow dismiss of pairing dialog
1158             break;
1159         }
1160 
1161         case HCI_EVENT_PIN_CODE_REQUEST:
1162             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1163             // non-bondable mode: pin code negative reply will be sent
1164             if (!hci_stack->bondable){
1165                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1166                 hci_run();
1167                 return;
1168             }
1169             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1170             if (!hci_stack->remote_device_db) break;
1171             bt_flip_addr(addr, &packet[2]);
1172             hci_stack->remote_device_db->delete_link_key(&addr);
1173             break;
1174 
1175         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1176             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1177             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1178             break;
1179 
1180         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1181             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1182             if (!hci_stack->ssp_auto_accept) break;
1183             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1184             break;
1185 
1186         case HCI_EVENT_USER_PASSKEY_REQUEST:
1187             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1188             if (!hci_stack->ssp_auto_accept) break;
1189             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1190             break;
1191 
1192         case HCI_EVENT_ENCRYPTION_CHANGE:
1193             handle = READ_BT_16(packet, 3);
1194             conn = hci_connection_for_handle(handle);
1195             if (!conn) break;
1196             if (packet[2] == 0) {
1197                 if (packet[5]){
1198                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1199                 } else {
1200                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1201                 }
1202             }
1203             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1204             break;
1205 
1206         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1207             handle = READ_BT_16(packet, 3);
1208             conn = hci_connection_for_handle(handle);
1209             if (!conn) break;
1210 
1211             // dedicated bonding: send result and disconnect
1212             if (conn->bonding_flags & BONDING_DEDICATED){
1213                 conn->bonding_flags &= ~BONDING_DEDICATED;
1214                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1215                 conn->bonding_status = packet[2];
1216                 break;
1217             }
1218 
1219             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1220                 // link key sufficient for requested security
1221                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1222                 break;
1223             }
1224             // not enough
1225             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1226             break;
1227 
1228 #ifndef EMBEDDED
1229         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1230             if (!hci_stack->remote_device_db) break;
1231             if (packet[2]) break; // status not ok
1232             bt_flip_addr(addr, &packet[3]);
1233             // fix for invalid remote names - terminate on 0xff
1234             for (i=0; i<248;i++){
1235                 if (packet[9+i] == 0xff){
1236                     packet[9+i] = 0;
1237                     break;
1238                 }
1239             }
1240             memset(&device_name, 0, sizeof(device_name_t));
1241             strncpy((char*) device_name, (char*) &packet[9], 248);
1242             hci_stack->remote_device_db->put_name(&addr, &device_name);
1243             break;
1244 
1245         case HCI_EVENT_INQUIRY_RESULT:
1246         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
1247             if (!hci_stack->remote_device_db) break;
1248             // first send inq result packet
1249             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1250             // then send cached remote names
1251             int offset = 3;
1252             for (i=0; i<packet[2];i++){
1253                 bt_flip_addr(addr, &packet[offset]);
1254                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
1255                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
1256                     hci_emit_remote_name_cached(&addr, &device_name);
1257                 }
1258             }
1259             return;
1260         }
1261 #endif
1262 
1263         // HCI_EVENT_DISCONNECTION_COMPLETE
1264         // has been split, to first notify stack before shutting connection down
1265         // see end of function, too.
1266         case HCI_EVENT_DISCONNECTION_COMPLETE:
1267             if (packet[2]) break;   // status != 0
1268             handle = READ_BT_16(packet, 3);
1269             hci_connection_t * conn = hci_connection_for_handle(handle);
1270             if (!conn) break;       // no conn struct anymore
1271             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1272             break;
1273 
1274         case HCI_EVENT_HARDWARE_ERROR:
1275             if(hci_stack->control && hci_stack->control->hw_error){
1276                 (*hci_stack->control->hw_error)();
1277             } else {
1278                 // if no special requests, just reboot stack
1279                 hci_power_control_off();
1280                 hci_power_control_on();
1281             }
1282             break;
1283 
1284         case DAEMON_EVENT_HCI_PACKET_SENT:
1285             // release packet buffer only for asynchronous transport and if there are not further fragements
1286             if (hci_transport_synchronous()) {
1287                 log_error("Synchronous HCI Transport shouldn't send DAEMON_EVENT_HCI_PACKET_SENT");
1288                 return; // instead of break: to avoid re-entering hci_run()
1289             }
1290             if (hci_stack->acl_fragmentation_total_size) break;
1291             hci_release_packet_buffer();
1292             break;
1293 
1294 #ifdef HAVE_BLE
1295         case HCI_EVENT_LE_META:
1296             switch (packet[2]){
1297                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1298                     log_info("advertising report received");
1299                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1300                     le_handle_advertisement_report(packet, size);
1301                     break;
1302                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1303                     // Connection management
1304                     bt_flip_addr(addr, &packet[8]);
1305                     addr_type = (bd_addr_type_t)packet[7];
1306                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1307                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1308                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1309                     if (packet[3]){
1310                         if (conn){
1311                             // outgoing connection failed, remove entry
1312                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1313                             btstack_memory_hci_connection_free( conn );
1314                         }
1315                         // if authentication error, also delete link key
1316                         if (packet[3] == 0x05) {
1317                             hci_drop_link_key_for_bd_addr(&addr);
1318                         }
1319                         break;
1320                     }
1321                     if (!conn){
1322                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1323                     }
1324                     if (!conn){
1325                         // no memory
1326                         break;
1327                     }
1328 
1329                     conn->state = OPEN;
1330                     conn->con_handle = READ_BT_16(packet, 4);
1331 
1332                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1333 
1334                     // restart timer
1335                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1336                     // run_loop_add_timer(&conn->timeout);
1337 
1338                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1339 
1340                     hci_emit_nr_connections_changed();
1341                     break;
1342 
1343             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
1344 
1345                 default:
1346                     break;
1347             }
1348             break;
1349 #endif
1350         default:
1351             break;
1352     }
1353 
1354     // handle BT initialization
1355     if (hci_stack->state == HCI_STATE_INITIALIZING){
1356         hci_initializing_event_handler(packet, size);
1357     }
1358 
1359     // help with BT sleep
1360     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1361         && hci_stack->substate == 1
1362         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1363         hci_stack->substate++;
1364     }
1365 
1366     // notify upper stack
1367     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1368 
1369     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1370     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1371         if (!packet[2]){
1372             handle = READ_BT_16(packet, 3);
1373             hci_connection_t * conn = hci_connection_for_handle(handle);
1374             if (conn) {
1375                 uint8_t status = conn->bonding_status;
1376                 uint16_t flags = conn->bonding_flags;
1377                 bd_addr_t bd_address;
1378                 memcpy(&bd_address, conn->address, 6);
1379                 hci_shutdown_connection(conn);
1380                 // connection struct is gone, don't access anymore
1381                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1382                     hci_emit_dedicated_bonding_result(bd_address, status);
1383                 }
1384             }
1385         }
1386     }
1387 
1388 	// execute main loop
1389 	hci_run();
1390 }
1391 
1392 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1393     hci_dump_packet(packet_type, 1, packet, size);
1394     switch (packet_type) {
1395         case HCI_EVENT_PACKET:
1396             event_handler(packet, size);
1397             break;
1398         case HCI_ACL_DATA_PACKET:
1399             acl_handler(packet, size);
1400             break;
1401         default:
1402             break;
1403     }
1404 }
1405 
1406 /** Register HCI packet handlers */
1407 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1408     hci_stack->packet_handler = handler;
1409 }
1410 
1411 static void hci_state_reset(){
1412     // no connections yet
1413     hci_stack->connections = NULL;
1414 
1415     // keep discoverable/connectable as this has been requested by the client(s)
1416     // hci_stack->discoverable = 0;
1417     // hci_stack->connectable = 0;
1418     // hci_stack->bondable = 1;
1419 
1420     // buffer is free
1421     hci_stack->hci_packet_buffer_reserved = 0;
1422 
1423     // no pending cmds
1424     hci_stack->decline_reason = 0;
1425     hci_stack->new_scan_enable_value = 0xff;
1426 
1427     // LE
1428     hci_stack->adv_addr_type = 0;
1429     memset(hci_stack->adv_address, 0, 6);
1430     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1431     hci_stack->le_scan_type = 0xff;
1432     hci_stack->le_connection_parameter_range.le_conn_interval_min = 0x0006;
1433     hci_stack->le_connection_parameter_range.le_conn_interval_max = 0x0C80;
1434     hci_stack->le_connection_parameter_range.le_conn_latency_min = 0x0000;
1435     hci_stack->le_connection_parameter_range.le_conn_latency_max = 0x03E8;
1436     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 0x000A;
1437     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 0x0C80;
1438 }
1439 
1440 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1441 
1442 #ifdef HAVE_MALLOC
1443     if (!hci_stack) {
1444         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1445     }
1446 #else
1447     hci_stack = &hci_stack_static;
1448 #endif
1449     memset(hci_stack, 0, sizeof(hci_stack_t));
1450 
1451     // reference to use transport layer implementation
1452     hci_stack->hci_transport = transport;
1453 
1454     // references to used control implementation
1455     hci_stack->control = control;
1456 
1457     // reference to used config
1458     hci_stack->config = config;
1459 
1460     // higher level handler
1461     hci_stack->packet_handler = dummy_handler;
1462 
1463     // store and open remote device db
1464     hci_stack->remote_device_db = remote_device_db;
1465     if (hci_stack->remote_device_db) {
1466         hci_stack->remote_device_db->open();
1467     }
1468 
1469     // max acl payload size defined in config.h
1470     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1471 
1472     // register packet handlers with transport
1473     transport->register_packet_handler(&packet_handler);
1474 
1475     hci_stack->state = HCI_STATE_OFF;
1476 
1477     // class of device
1478     hci_stack->class_of_device = 0x007a020c; // Smartphone
1479 
1480     // bondable by default
1481     hci_stack->bondable = 1;
1482 
1483     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1484     hci_stack->ssp_enable = 1;
1485     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1486     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1487     hci_stack->ssp_auto_accept = 1;
1488 
1489     hci_state_reset();
1490 }
1491 
1492 void hci_close(){
1493     // close remote device db
1494     if (hci_stack->remote_device_db) {
1495         hci_stack->remote_device_db->close();
1496     }
1497     while (hci_stack->connections) {
1498         // cancel all l2cap connections
1499         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1500         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1501     }
1502     hci_power_control(HCI_POWER_OFF);
1503 
1504 #ifdef HAVE_MALLOC
1505     free(hci_stack);
1506 #endif
1507     hci_stack = NULL;
1508 }
1509 
1510 void hci_set_class_of_device(uint32_t class_of_device){
1511     hci_stack->class_of_device = class_of_device;
1512 }
1513 
1514 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
1515 void hci_set_bd_addr(bd_addr_t addr){
1516     memcpy(hci_stack->custom_bd_addr, addr, 6);
1517     hci_stack->custom_bd_addr_set = 1;
1518 }
1519 
1520 void hci_disable_l2cap_timeout_check(){
1521     disable_l2cap_timeouts = 1;
1522 }
1523 // State-Module-Driver overview
1524 // state                    module  low-level
1525 // HCI_STATE_OFF             off      close
1526 // HCI_STATE_INITIALIZING,   on       open
1527 // HCI_STATE_WORKING,        on       open
1528 // HCI_STATE_HALTING,        on       open
1529 // HCI_STATE_SLEEPING,    off/sleep   close
1530 // HCI_STATE_FALLING_ASLEEP  on       open
1531 
1532 static int hci_power_control_on(void){
1533 
1534     // power on
1535     int err = 0;
1536     if (hci_stack->control && hci_stack->control->on){
1537         err = (*hci_stack->control->on)(hci_stack->config);
1538     }
1539     if (err){
1540         log_error( "POWER_ON failed");
1541         hci_emit_hci_open_failed();
1542         return err;
1543     }
1544 
1545     // open low-level device
1546     err = hci_stack->hci_transport->open(hci_stack->config);
1547     if (err){
1548         log_error( "HCI_INIT failed, turning Bluetooth off again");
1549         if (hci_stack->control && hci_stack->control->off){
1550             (*hci_stack->control->off)(hci_stack->config);
1551         }
1552         hci_emit_hci_open_failed();
1553         return err;
1554     }
1555     return 0;
1556 }
1557 
1558 static void hci_power_control_off(void){
1559 
1560     log_info("hci_power_control_off");
1561 
1562     // close low-level device
1563     hci_stack->hci_transport->close(hci_stack->config);
1564 
1565     log_info("hci_power_control_off - hci_transport closed");
1566 
1567     // power off
1568     if (hci_stack->control && hci_stack->control->off){
1569         (*hci_stack->control->off)(hci_stack->config);
1570     }
1571 
1572     log_info("hci_power_control_off - control closed");
1573 
1574     hci_stack->state = HCI_STATE_OFF;
1575 }
1576 
1577 static void hci_power_control_sleep(void){
1578 
1579     log_info("hci_power_control_sleep");
1580 
1581 #if 0
1582     // don't close serial port during sleep
1583 
1584     // close low-level device
1585     hci_stack->hci_transport->close(hci_stack->config);
1586 #endif
1587 
1588     // sleep mode
1589     if (hci_stack->control && hci_stack->control->sleep){
1590         (*hci_stack->control->sleep)(hci_stack->config);
1591     }
1592 
1593     hci_stack->state = HCI_STATE_SLEEPING;
1594 }
1595 
1596 static int hci_power_control_wake(void){
1597 
1598     log_info("hci_power_control_wake");
1599 
1600     // wake on
1601     if (hci_stack->control && hci_stack->control->wake){
1602         (*hci_stack->control->wake)(hci_stack->config);
1603     }
1604 
1605 #if 0
1606     // open low-level device
1607     int err = hci_stack->hci_transport->open(hci_stack->config);
1608     if (err){
1609         log_error( "HCI_INIT failed, turning Bluetooth off again");
1610         if (hci_stack->control && hci_stack->control->off){
1611             (*hci_stack->control->off)(hci_stack->config);
1612         }
1613         hci_emit_hci_open_failed();
1614         return err;
1615     }
1616 #endif
1617 
1618     return 0;
1619 }
1620 
1621 static void hci_power_transition_to_initializing(void){
1622     // set up state machine
1623     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1624     hci_stack->hci_packet_buffer_reserved = 0;
1625     hci_stack->state = HCI_STATE_INITIALIZING;
1626     hci_stack->substate = 0;
1627 }
1628 
1629 int hci_power_control(HCI_POWER_MODE power_mode){
1630 
1631     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1632 
1633     int err = 0;
1634     switch (hci_stack->state){
1635 
1636         case HCI_STATE_OFF:
1637             switch (power_mode){
1638                 case HCI_POWER_ON:
1639                     err = hci_power_control_on();
1640                     if (err) {
1641                         log_error("hci_power_control_on() error %u", err);
1642                         return err;
1643                     }
1644                     hci_power_transition_to_initializing();
1645                     break;
1646                 case HCI_POWER_OFF:
1647                     // do nothing
1648                     break;
1649                 case HCI_POWER_SLEEP:
1650                     // do nothing (with SLEEP == OFF)
1651                     break;
1652             }
1653             break;
1654 
1655         case HCI_STATE_INITIALIZING:
1656             switch (power_mode){
1657                 case HCI_POWER_ON:
1658                     // do nothing
1659                     break;
1660                 case HCI_POWER_OFF:
1661                     // no connections yet, just turn it off
1662                     hci_power_control_off();
1663                     break;
1664                 case HCI_POWER_SLEEP:
1665                     // no connections yet, just turn it off
1666                     hci_power_control_sleep();
1667                     break;
1668             }
1669             break;
1670 
1671         case HCI_STATE_WORKING:
1672             switch (power_mode){
1673                 case HCI_POWER_ON:
1674                     // do nothing
1675                     break;
1676                 case HCI_POWER_OFF:
1677                     // see hci_run
1678                     hci_stack->state = HCI_STATE_HALTING;
1679                     break;
1680                 case HCI_POWER_SLEEP:
1681                     // see hci_run
1682                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1683                     hci_stack->substate = 0;
1684                     break;
1685             }
1686             break;
1687 
1688         case HCI_STATE_HALTING:
1689             switch (power_mode){
1690                 case HCI_POWER_ON:
1691                     hci_power_transition_to_initializing();
1692                     break;
1693                 case HCI_POWER_OFF:
1694                     // do nothing
1695                     break;
1696                 case HCI_POWER_SLEEP:
1697                     // see hci_run
1698                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1699                     hci_stack->substate = 0;
1700                     break;
1701             }
1702             break;
1703 
1704         case HCI_STATE_FALLING_ASLEEP:
1705             switch (power_mode){
1706                 case HCI_POWER_ON:
1707 
1708 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1709                     // nothing to do, if H4 supports power management
1710                     if (bt_control_iphone_power_management_enabled()){
1711                         hci_stack->state = HCI_STATE_INITIALIZING;
1712                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1713                         break;
1714                     }
1715 #endif
1716                     hci_power_transition_to_initializing();
1717                     break;
1718                 case HCI_POWER_OFF:
1719                     // see hci_run
1720                     hci_stack->state = HCI_STATE_HALTING;
1721                     break;
1722                 case HCI_POWER_SLEEP:
1723                     // do nothing
1724                     break;
1725             }
1726             break;
1727 
1728         case HCI_STATE_SLEEPING:
1729             switch (power_mode){
1730                 case HCI_POWER_ON:
1731 
1732 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1733                     // nothing to do, if H4 supports power management
1734                     if (bt_control_iphone_power_management_enabled()){
1735                         hci_stack->state = HCI_STATE_INITIALIZING;
1736                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1737                         hci_update_scan_enable();
1738                         break;
1739                     }
1740 #endif
1741                     err = hci_power_control_wake();
1742                     if (err) return err;
1743                     hci_power_transition_to_initializing();
1744                     break;
1745                 case HCI_POWER_OFF:
1746                     hci_stack->state = HCI_STATE_HALTING;
1747                     break;
1748                 case HCI_POWER_SLEEP:
1749                     // do nothing
1750                     break;
1751             }
1752             break;
1753     }
1754 
1755     // create internal event
1756 	hci_emit_state();
1757 
1758 	// trigger next/first action
1759 	hci_run();
1760 
1761     return 0;
1762 }
1763 
1764 static void hci_update_scan_enable(void){
1765     // 2 = page scan, 1 = inq scan
1766     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1767     hci_run();
1768 }
1769 
1770 void hci_discoverable_control(uint8_t enable){
1771     if (enable) enable = 1; // normalize argument
1772 
1773     if (hci_stack->discoverable == enable){
1774         hci_emit_discoverable_enabled(hci_stack->discoverable);
1775         return;
1776     }
1777 
1778     hci_stack->discoverable = enable;
1779     hci_update_scan_enable();
1780 }
1781 
1782 void hci_connectable_control(uint8_t enable){
1783     if (enable) enable = 1; // normalize argument
1784 
1785     // don't emit event
1786     if (hci_stack->connectable == enable) return;
1787 
1788     hci_stack->connectable = enable;
1789     hci_update_scan_enable();
1790 }
1791 
1792 bd_addr_t * hci_local_bd_addr(void){
1793     return &hci_stack->local_bd_addr;
1794 }
1795 
1796 void hci_run(){
1797 
1798     hci_connection_t * connection;
1799     linked_item_t * it;
1800 
1801     // send continuation fragments first, as they block the prepared packet buffer
1802     if (hci_stack->acl_fragmentation_total_size > 0) {
1803         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1804         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1805             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1806             if (connection) {
1807                 hci_send_acl_packet_fragments(connection);
1808                 return;
1809             }
1810             // connection gone -> discard further fragments
1811             hci_stack->acl_fragmentation_total_size = 0;
1812             hci_stack->acl_fragmentation_pos = 0;
1813         }
1814     }
1815 
1816     if (!hci_can_send_command_packet_now()) return;
1817 
1818     // global/non-connection oriented commands
1819 
1820     // decline incoming connections
1821     if (hci_stack->decline_reason){
1822         uint8_t reason = hci_stack->decline_reason;
1823         hci_stack->decline_reason = 0;
1824         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1825         return;
1826     }
1827 
1828     // send scan enable
1829     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1830         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1831         hci_stack->new_scan_enable_value = 0xff;
1832         return;
1833     }
1834 
1835 #ifdef HAVE_BLE
1836     // handle le scan
1837     if (hci_stack->state == HCI_STATE_WORKING){
1838         switch(hci_stack->le_scanning_state){
1839             case LE_START_SCAN:
1840                 hci_stack->le_scanning_state = LE_SCANNING;
1841                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1842                 return;
1843 
1844             case LE_STOP_SCAN:
1845                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1846                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1847                 return;
1848             default:
1849                 break;
1850         }
1851         if (hci_stack->le_scan_type != 0xff){
1852             // defaults: active scanning, accept all advertisement packets
1853             int scan_type = hci_stack->le_scan_type;
1854             hci_stack->le_scan_type = 0xff;
1855             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0);
1856             return;
1857         }
1858     }
1859 #endif
1860 
1861     // send pending HCI commands
1862     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1863         connection = (hci_connection_t *) it;
1864 
1865         switch(connection->state){
1866             case SEND_CREATE_CONNECTION:
1867                 switch(connection->address_type){
1868                     case BD_ADDR_TYPE_CLASSIC:
1869                         log_info("sending hci_create_connection");
1870                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1871                         break;
1872                     default:
1873 #ifdef HAVE_BLE
1874                         log_info("sending hci_le_create_connection");
1875                         hci_send_cmd(&hci_le_create_connection,
1876                                      0x0060,    // scan interval: 60 ms
1877                                      0x0030,    // scan interval: 30 ms
1878                                      0,         // don't use whitelist
1879                                      connection->address_type, // peer address type
1880                                      connection->address,      // peer bd addr
1881                                      hci_stack->adv_addr_type, // our addr type:
1882                                      0x0008,    // conn interval min
1883                                      0x0018,    // conn interval max
1884                                      0,         // conn latency
1885                                      0x0048,    // supervision timeout
1886                                      0x0001,    // min ce length
1887                                      0x0001     // max ce length
1888                                      );
1889 
1890                         connection->state = SENT_CREATE_CONNECTION;
1891 #endif
1892                         break;
1893                 }
1894                 return;
1895 
1896             case RECEIVED_CONNECTION_REQUEST:
1897                 log_info("sending hci_accept_connection_request");
1898                 connection->state = ACCEPTED_CONNECTION_REQUEST;
1899                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1900                 return;
1901 
1902 #ifdef HAVE_BLE
1903             case SEND_CANCEL_CONNECTION:
1904                 connection->state = SENT_CANCEL_CONNECTION;
1905                 hci_send_cmd(&hci_le_create_connection_cancel);
1906                 return;
1907 #endif
1908             case SEND_DISCONNECT:
1909                 connection->state = SENT_DISCONNECT;
1910                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1911                 return;
1912 
1913             default:
1914                 break;
1915         }
1916 
1917         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1918             log_info("responding to link key request");
1919             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1920             link_key_t link_key;
1921             link_key_type_t link_key_type;
1922             if ( hci_stack->remote_device_db
1923               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1924               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1925                connection->link_key_type = link_key_type;
1926                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1927             } else {
1928                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1929             }
1930             return;
1931         }
1932 
1933         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1934             log_info("denying to pin request");
1935             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1936             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1937             return;
1938         }
1939 
1940         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1941             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1942             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1943             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1944                 // tweak authentication requirements
1945                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1946                 if (connection->bonding_flags & BONDING_DEDICATED){
1947                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1948                 }
1949                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1950                     authreq |= 1;
1951                 }
1952                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1953             } else {
1954                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1955             }
1956             return;
1957         }
1958 
1959         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1960             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1961             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1962             return;
1963         }
1964 
1965         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1966             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1967             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1968             return;
1969         }
1970 
1971         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1972             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1973             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1974             return;
1975         }
1976 
1977         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1978             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1979             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1980             return;
1981         }
1982         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1983             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1984             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
1985             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1986             return;
1987         }
1988         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1989             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1990             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1991             return;
1992         }
1993         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1994             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1995             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1996             return;
1997         }
1998 
1999 #ifdef HAVE_BLE
2000         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2001             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2002 
2003             uint16_t connection_interval_min = connection->le_conn_interval_min;
2004             connection->le_conn_interval_min = 0;
2005             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2006                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2007                 0x0000, 0xffff);
2008         }
2009 #endif
2010     }
2011 
2012     switch (hci_stack->state){
2013         case HCI_STATE_INITIALIZING:
2014             hci_initializing_state_machine();
2015             break;
2016 
2017         case HCI_STATE_HALTING:
2018 
2019             log_info("HCI_STATE_HALTING");
2020             // close all open connections
2021             connection =  (hci_connection_t *) hci_stack->connections;
2022             if (connection){
2023 
2024                 // send disconnect
2025                 if (!hci_can_send_command_packet_now()) return;
2026 
2027                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2028                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2029 
2030                 // send disconnected event right away - causes higher layer connections to get closed, too.
2031                 hci_shutdown_connection(connection);
2032                 return;
2033             }
2034             log_info("HCI_STATE_HALTING, calling off");
2035 
2036             // switch mode
2037             hci_power_control_off();
2038 
2039             log_info("HCI_STATE_HALTING, emitting state");
2040             hci_emit_state();
2041             log_info("HCI_STATE_HALTING, done");
2042             break;
2043 
2044         case HCI_STATE_FALLING_ASLEEP:
2045             switch(hci_stack->substate) {
2046                 case 0:
2047                     log_info("HCI_STATE_FALLING_ASLEEP");
2048                     // close all open connections
2049                     connection =  (hci_connection_t *) hci_stack->connections;
2050 
2051 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2052                     // don't close connections, if H4 supports power management
2053                     if (bt_control_iphone_power_management_enabled()){
2054                         connection = NULL;
2055                     }
2056 #endif
2057                     if (connection){
2058 
2059                         // send disconnect
2060                         if (!hci_can_send_command_packet_now()) return;
2061 
2062                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2063                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2064 
2065                         // send disconnected event right away - causes higher layer connections to get closed, too.
2066                         hci_shutdown_connection(connection);
2067                         return;
2068                     }
2069 
2070                     if (hci_classic_supported()){
2071                         // disable page and inquiry scan
2072                         if (!hci_can_send_command_packet_now()) return;
2073 
2074                         log_info("HCI_STATE_HALTING, disabling inq scans");
2075                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
2076 
2077                         // continue in next sub state
2078                         hci_stack->substate++;
2079                         break;
2080                     }
2081                     // fall through for ble-only chips
2082 
2083                 case 2:
2084                     log_info("HCI_STATE_HALTING, calling sleep");
2085 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2086                     // don't actually go to sleep, if H4 supports power management
2087                     if (bt_control_iphone_power_management_enabled()){
2088                         // SLEEP MODE reached
2089                         hci_stack->state = HCI_STATE_SLEEPING;
2090                         hci_emit_state();
2091                         break;
2092                     }
2093 #endif
2094                     // switch mode
2095                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2096                     hci_emit_state();
2097                     break;
2098 
2099                 default:
2100                     break;
2101             }
2102             break;
2103 
2104         default:
2105             break;
2106     }
2107 }
2108 
2109 int hci_send_cmd_packet(uint8_t *packet, int size){
2110     bd_addr_t addr;
2111     hci_connection_t * conn;
2112     // house-keeping
2113 
2114     // create_connection?
2115     if (IS_COMMAND(packet, hci_create_connection)){
2116         bt_flip_addr(addr, &packet[3]);
2117         log_info("Create_connection to %s", bd_addr_to_str(addr));
2118 
2119         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2120         if (!conn){
2121             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2122             if (!conn){
2123                 // notify client that alloc failed
2124                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2125                 return 0; // don't sent packet to controller
2126             }
2127             conn->state = SEND_CREATE_CONNECTION;
2128         }
2129         log_info("conn state %u", conn->state);
2130         switch (conn->state){
2131             // if connection active exists
2132             case OPEN:
2133                 // and OPEN, emit connection complete command, don't send to controller
2134                 hci_emit_connection_complete(conn, 0);
2135                 return 0;
2136             case SEND_CREATE_CONNECTION:
2137                 // connection created by hci, e.g. dedicated bonding
2138                 break;
2139             default:
2140                 // otherwise, just ignore as it is already in the open process
2141                 return 0;
2142         }
2143         conn->state = SENT_CREATE_CONNECTION;
2144     }
2145 
2146     if (IS_COMMAND(packet, hci_link_key_request_reply)){
2147         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
2148     }
2149     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
2150         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
2151     }
2152 
2153     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2154         if (hci_stack->remote_device_db){
2155             bt_flip_addr(addr, &packet[3]);
2156             hci_stack->remote_device_db->delete_link_key(&addr);
2157         }
2158     }
2159 
2160     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2161     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2162         bt_flip_addr(addr, &packet[3]);
2163         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2164         if (conn){
2165             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2166         }
2167     }
2168 
2169     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2170     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2171     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2172     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2173         bt_flip_addr(addr, &packet[3]);
2174         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2175         if (conn){
2176             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2177         }
2178     }
2179 
2180 #ifdef HAVE_BLE
2181     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2182         hci_stack->adv_addr_type = packet[8];
2183     }
2184     if (IS_COMMAND(packet, hci_le_set_random_address)){
2185         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2186     }
2187 #endif
2188 
2189     hci_stack->num_cmd_packets--;
2190 
2191     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2192     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2193 
2194     // release packet buffer for synchronous transport implementations
2195     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2196         hci_stack->hci_packet_buffer_reserved = 0;
2197     }
2198 
2199     return err;
2200 }
2201 
2202 // disconnect because of security block
2203 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2204     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2205     if (!connection) return;
2206     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2207 }
2208 
2209 
2210 // Configure Secure Simple Pairing
2211 
2212 // enable will enable SSP during init
2213 void hci_ssp_set_enable(int enable){
2214     hci_stack->ssp_enable = enable;
2215 }
2216 
2217 int hci_local_ssp_activated(){
2218     return hci_ssp_supported() && hci_stack->ssp_enable;
2219 }
2220 
2221 // if set, BTstack will respond to io capability request using authentication requirement
2222 void hci_ssp_set_io_capability(int io_capability){
2223     hci_stack->ssp_io_capability = io_capability;
2224 }
2225 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2226     hci_stack->ssp_authentication_requirement = authentication_requirement;
2227 }
2228 
2229 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2230 void hci_ssp_set_auto_accept(int auto_accept){
2231     hci_stack->ssp_auto_accept = auto_accept;
2232 }
2233 
2234 /**
2235  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2236  */
2237 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2238 
2239     if (!hci_can_send_command_packet_now()){
2240         log_error("hci_send_cmd called but cannot send packet now");
2241         return 0;
2242     }
2243 
2244     // for HCI INITIALIZATION
2245     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2246     hci_stack->last_cmd_opcode = cmd->opcode;
2247 
2248     hci_reserve_packet_buffer();
2249     uint8_t * packet = hci_stack->hci_packet_buffer;
2250 
2251     va_list argptr;
2252     va_start(argptr, cmd);
2253     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
2254     va_end(argptr);
2255 
2256     return hci_send_cmd_packet(packet, size);
2257 }
2258 
2259 // Create various non-HCI events.
2260 // TODO: generalize, use table similar to hci_create_command
2261 
2262 void hci_emit_state(){
2263     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2264     uint8_t event[3];
2265     event[0] = BTSTACK_EVENT_STATE;
2266     event[1] = sizeof(event) - 2;
2267     event[2] = hci_stack->state;
2268     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2269     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2270 }
2271 
2272 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2273     uint8_t event[13];
2274     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2275     event[1] = sizeof(event) - 2;
2276     event[2] = status;
2277     bt_store_16(event, 3, conn->con_handle);
2278     bt_flip_addr(&event[5], conn->address);
2279     event[11] = 1; // ACL connection
2280     event[12] = 0; // encryption disabled
2281     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2282     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2283 }
2284 
2285 void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t * address, uint16_t conn_handle, uint8_t status){
2286     uint8_t event[21];
2287     event[0] = HCI_EVENT_LE_META;
2288     event[1] = sizeof(event) - 2;
2289     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2290     event[3] = status;
2291     bt_store_16(event, 4, conn_handle);
2292     event[6] = 0; // TODO: role
2293     event[7] = address_type;
2294     bt_flip_addr(&event[8], *address);
2295     bt_store_16(event, 14, 0); // interval
2296     bt_store_16(event, 16, 0); // latency
2297     bt_store_16(event, 18, 0); // supervision timeout
2298     event[20] = 0; // master clock accuracy
2299     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2300     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2301 }
2302 
2303 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2304     uint8_t event[6];
2305     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2306     event[1] = sizeof(event) - 2;
2307     event[2] = 0; // status = OK
2308     bt_store_16(event, 3, handle);
2309     event[5] = reason;
2310     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2311     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2312 }
2313 
2314 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2315     if (disable_l2cap_timeouts) return;
2316     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2317     uint8_t event[4];
2318     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2319     event[1] = sizeof(event) - 2;
2320     bt_store_16(event, 2, conn->con_handle);
2321     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2322     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2323 }
2324 
2325 void hci_emit_nr_connections_changed(){
2326     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2327     uint8_t event[3];
2328     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2329     event[1] = sizeof(event) - 2;
2330     event[2] = nr_hci_connections();
2331     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2332     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2333 }
2334 
2335 void hci_emit_hci_open_failed(){
2336     log_info("BTSTACK_EVENT_POWERON_FAILED");
2337     uint8_t event[2];
2338     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2339     event[1] = sizeof(event) - 2;
2340     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2341     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2342 }
2343 
2344 #ifndef EMBEDDED
2345 void hci_emit_btstack_version() {
2346     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2347     uint8_t event[6];
2348     event[0] = BTSTACK_EVENT_VERSION;
2349     event[1] = sizeof(event) - 2;
2350     event[2] = BTSTACK_MAJOR;
2351     event[3] = BTSTACK_MINOR;
2352     bt_store_16(event, 4, BTSTACK_REVISION);
2353     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2354     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2355 }
2356 #endif
2357 
2358 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2359     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2360     uint8_t event[3];
2361     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2362     event[1] = sizeof(event) - 2;
2363     event[2] = enabled;
2364     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2365     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2366 }
2367 
2368 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2369     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2370     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2371     event[1] = sizeof(event) - 2 - 1;
2372     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
2373     bt_flip_addr(&event[3], *addr);
2374     memcpy(&event[9], name, 248);
2375 
2376     event[9+248] = 0;   // assert \0 for log_info
2377     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2378 
2379     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2380     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2381 }
2382 
2383 void hci_emit_discoverable_enabled(uint8_t enabled){
2384     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2385     uint8_t event[3];
2386     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2387     event[1] = sizeof(event) - 2;
2388     event[2] = enabled;
2389     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2390     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2391 }
2392 
2393 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2394     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2395     uint8_t event[5];
2396     int pos = 0;
2397     event[pos++] = GAP_SECURITY_LEVEL;
2398     event[pos++] = sizeof(event) - 2;
2399     bt_store_16(event, 2, con_handle);
2400     pos += 2;
2401     event[pos++] = level;
2402     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2403     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2404 }
2405 
2406 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2407     log_info("hci_emit_dedicated_bonding_result %u ", status);
2408     uint8_t event[9];
2409     int pos = 0;
2410     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2411     event[pos++] = sizeof(event) - 2;
2412     event[pos++] = status;
2413     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2414     pos += 6;
2415     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2416     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2417 }
2418 
2419 // query if remote side supports SSP
2420 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2421     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2422     if (!connection) return 0;
2423     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2424 }
2425 
2426 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2427     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2428 }
2429 
2430 // GAP API
2431 /**
2432  * @bbrief enable/disable bonding. default is enabled
2433  * @praram enabled
2434  */
2435 void gap_set_bondable_mode(int enable){
2436     hci_stack->bondable = enable ? 1 : 0;
2437 }
2438 
2439 /**
2440  * @brief map link keys to security levels
2441  */
2442 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2443     switch (link_key_type){
2444         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2445             return LEVEL_4;
2446         case COMBINATION_KEY:
2447         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2448             return LEVEL_3;
2449         default:
2450             return LEVEL_2;
2451     }
2452 }
2453 
2454 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2455     if (!connection) return LEVEL_0;
2456     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2457     return gap_security_level_for_link_key_type(connection->link_key_type);
2458 }
2459 
2460 
2461 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2462     log_info("gap_mitm_protection_required_for_security_level %u", level);
2463     return level > LEVEL_2;
2464 }
2465 
2466 /**
2467  * @brief get current security level
2468  */
2469 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2470     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2471     if (!connection) return LEVEL_0;
2472     return gap_security_level_for_connection(connection);
2473 }
2474 
2475 /**
2476  * @brief request connection to device to
2477  * @result GAP_AUTHENTICATION_RESULT
2478  */
2479 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2480     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2481     if (!connection){
2482         hci_emit_security_level(con_handle, LEVEL_0);
2483         return;
2484     }
2485     gap_security_level_t current_level = gap_security_level(con_handle);
2486     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2487     if (current_level >= requested_level){
2488         hci_emit_security_level(con_handle, current_level);
2489         return;
2490     }
2491 
2492     connection->requested_security_level = requested_level;
2493 
2494 #if 0
2495     // sending encryption request without a link key results in an error.
2496     // TODO: figure out how to use it properly
2497 
2498     // would enabling ecnryption suffice (>= LEVEL_2)?
2499     if (hci_stack->remote_device_db){
2500         link_key_type_t link_key_type;
2501         link_key_t      link_key;
2502         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2503             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2504                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2505                 return;
2506             }
2507         }
2508     }
2509 #endif
2510 
2511     // try to authenticate connection
2512     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2513     hci_run();
2514 }
2515 
2516 /**
2517  * @brief start dedicated bonding with device. disconnect after bonding
2518  * @param device
2519  * @param request MITM protection
2520  * @result GAP_DEDICATED_BONDING_COMPLETE
2521  */
2522 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2523 
2524     // create connection state machine
2525     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2526 
2527     if (!connection){
2528         return BTSTACK_MEMORY_ALLOC_FAILED;
2529     }
2530 
2531     // delete linkn key
2532     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2533 
2534     // configure LEVEL_2/3, dedicated bonding
2535     connection->state = SEND_CREATE_CONNECTION;
2536     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2537     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2538     connection->bonding_flags = BONDING_DEDICATED;
2539 
2540     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2541 
2542     // handle: connnection failure (connection complete != ok)
2543     // handle: authentication failure
2544     // handle: disconnect on done
2545 
2546     hci_run();
2547 
2548     return 0;
2549 }
2550 
2551 void gap_set_local_name(const char * local_name){
2552     hci_stack->local_name = local_name;
2553 }
2554 
2555 le_command_status_t le_central_start_scan(){
2556     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2557     hci_stack->le_scanning_state = LE_START_SCAN;
2558     hci_run();
2559     return BLE_PERIPHERAL_OK;
2560 }
2561 
2562 le_command_status_t le_central_stop_scan(){
2563     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2564     hci_stack->le_scanning_state = LE_STOP_SCAN;
2565     hci_run();
2566     return BLE_PERIPHERAL_OK;
2567 }
2568 
2569 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2570     hci_stack->le_scan_type     = scan_type;
2571     hci_stack->le_scan_interval = scan_interval;
2572     hci_stack->le_scan_window   = scan_window;
2573     hci_run();
2574 }
2575 
2576 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2577     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2578     if (!conn){
2579         log_info("le_central_connect: no connection exists yet, creating context");
2580         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2581         if (!conn){
2582             // notify client that alloc failed
2583             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
2584             log_info("le_central_connect: failed to alloc hci_connection_t");
2585             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2586         }
2587         conn->state = SEND_CREATE_CONNECTION;
2588         log_info("le_central_connect: send create connection next");
2589         hci_run();
2590         return BLE_PERIPHERAL_OK;
2591     }
2592 
2593     if (!hci_is_le_connection(conn) ||
2594         conn->state == SEND_CREATE_CONNECTION ||
2595         conn->state == SENT_CREATE_CONNECTION) {
2596         hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
2597         log_error("le_central_connect: classic connection or connect is already being created");
2598         return BLE_PERIPHERAL_IN_WRONG_STATE;
2599     }
2600 
2601     log_info("le_central_connect: context exists with state %u", conn->state);
2602     hci_emit_le_connection_complete(conn->address_type, &conn->address, conn->con_handle, 0);
2603     hci_run();
2604     return BLE_PERIPHERAL_OK;
2605 }
2606 
2607 // @assumption: only a single outgoing LE Connection exists
2608 static hci_connection_t * le_central_get_outgoing_connection(){
2609     linked_item_t *it;
2610     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
2611         hci_connection_t * conn = (hci_connection_t *) it;
2612         if (!hci_is_le_connection(conn)) continue;
2613         switch (conn->state){
2614             case SEND_CREATE_CONNECTION:
2615             case SENT_CREATE_CONNECTION:
2616                 return conn;
2617             default:
2618                 break;
2619         };
2620     }
2621     return NULL;
2622 }
2623 
2624 le_command_status_t le_central_connect_cancel(){
2625     hci_connection_t * conn = le_central_get_outgoing_connection();
2626     switch (conn->state){
2627         case SEND_CREATE_CONNECTION:
2628             // skip sending create connection and emit event instead
2629             hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2630             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2631             btstack_memory_hci_connection_free( conn );
2632             break;
2633         case SENT_CREATE_CONNECTION:
2634             // request to send cancel connection
2635             conn->state = SEND_CANCEL_CONNECTION;
2636             hci_run();
2637             break;
2638         default:
2639             break;
2640     }
2641     return BLE_PERIPHERAL_OK;
2642 }
2643 
2644 /**
2645  * @brief Updates the connection parameters for a given LE connection
2646  * @param handle
2647  * @param conn_interval_min (unit: 1.25ms)
2648  * @param conn_interval_max (unit: 1.25ms)
2649  * @param conn_latency
2650  * @param supervision_timeout (unit: 10ms)
2651  * @returns 0 if ok
2652  */
2653 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2654     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2655     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2656     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2657     connection->le_conn_interval_min = conn_interval_min;
2658     connection->le_conn_interval_max = conn_interval_max;
2659     connection->le_conn_latency = conn_latency;
2660     connection->le_supervision_timeout = supervision_timeout;
2661     return 0;
2662 }
2663 
2664 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2665     hci_connection_t * conn = hci_connection_for_handle(handle);
2666     if (!conn){
2667         hci_emit_disconnection_complete(handle, 0);
2668         return BLE_PERIPHERAL_OK;
2669     }
2670     conn->state = SEND_DISCONNECT;
2671     hci_run();
2672     return BLE_PERIPHERAL_OK;
2673 }
2674 
2675 void hci_disconnect_all(){
2676     linked_list_iterator_t it;
2677     linked_list_iterator_init(&it, &hci_stack->connections);
2678     while (linked_list_iterator_has_next(&it)){
2679         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
2680         if (con->state == SENT_DISCONNECT) continue;
2681         con->state = SEND_DISCONNECT;
2682     }
2683     hci_run();
2684 }
2685