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