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