xref: /btstack/src/hci.c (revision 507d06b8706f343b0b71782ceff40e11246399a7)
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()) break;
1296             if (hci_stack->acl_fragmentation_total_size) break;
1297             hci_release_packet_buffer();
1298             break;
1299 
1300 #ifdef HAVE_BLE
1301         case HCI_EVENT_LE_META:
1302             switch (packet[2]){
1303                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1304                     log_info("advertising report received");
1305                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1306                     le_handle_advertisement_report(packet, size);
1307                     break;
1308                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1309                     // Connection management
1310                     bt_flip_addr(addr, &packet[8]);
1311                     addr_type = (bd_addr_type_t)packet[7];
1312                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1313                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1314                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1315                     if (packet[3]){
1316                         if (conn){
1317                             // outgoing connection failed, remove entry
1318                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1319                             btstack_memory_hci_connection_free( conn );
1320                         }
1321                         // if authentication error, also delete link key
1322                         if (packet[3] == 0x05) {
1323                             hci_drop_link_key_for_bd_addr(&addr);
1324                         }
1325                         break;
1326                     }
1327                     if (!conn){
1328                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1329                     }
1330                     if (!conn){
1331                         // no memory
1332                         break;
1333                     }
1334 
1335                     conn->state = OPEN;
1336                     conn->con_handle = READ_BT_16(packet, 4);
1337 
1338                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1339 
1340                     // restart timer
1341                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1342                     // run_loop_add_timer(&conn->timeout);
1343 
1344                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1345 
1346                     hci_emit_nr_connections_changed();
1347                     break;
1348 
1349             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
1350 
1351                 default:
1352                     break;
1353             }
1354             break;
1355 #endif
1356         default:
1357             break;
1358     }
1359 
1360     // handle BT initialization
1361     if (hci_stack->state == HCI_STATE_INITIALIZING){
1362         hci_initializing_event_handler(packet, size);
1363     }
1364 
1365     // help with BT sleep
1366     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1367         && hci_stack->substate == 1
1368         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1369         hci_stack->substate++;
1370     }
1371 
1372     // notify upper stack
1373     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1374 
1375     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1376     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1377         if (!packet[2]){
1378             handle = READ_BT_16(packet, 3);
1379             hci_connection_t * conn = hci_connection_for_handle(handle);
1380             if (conn) {
1381                 uint8_t status = conn->bonding_status;
1382                 uint16_t flags = conn->bonding_flags;
1383                 bd_addr_t bd_address;
1384                 memcpy(&bd_address, conn->address, 6);
1385                 hci_shutdown_connection(conn);
1386                 // connection struct is gone, don't access anymore
1387                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1388                     hci_emit_dedicated_bonding_result(bd_address, status);
1389                 }
1390             }
1391         }
1392     }
1393 
1394 	// execute main loop
1395 	hci_run();
1396 }
1397 
1398 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1399     hci_dump_packet(packet_type, 1, packet, size);
1400     switch (packet_type) {
1401         case HCI_EVENT_PACKET:
1402             event_handler(packet, size);
1403             break;
1404         case HCI_ACL_DATA_PACKET:
1405             acl_handler(packet, size);
1406             break;
1407         default:
1408             break;
1409     }
1410 }
1411 
1412 /** Register HCI packet handlers */
1413 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1414     hci_stack->packet_handler = handler;
1415 }
1416 
1417 static void hci_state_reset(){
1418     // no connections yet
1419     hci_stack->connections = NULL;
1420 
1421     // keep discoverable/connectable as this has been requested by the client(s)
1422     // hci_stack->discoverable = 0;
1423     // hci_stack->connectable = 0;
1424     // hci_stack->bondable = 1;
1425 
1426     // buffer is free
1427     hci_stack->hci_packet_buffer_reserved = 0;
1428 
1429     // no pending cmds
1430     hci_stack->decline_reason = 0;
1431     hci_stack->new_scan_enable_value = 0xff;
1432 
1433     // LE
1434     hci_stack->adv_addr_type = 0;
1435     memset(hci_stack->adv_address, 0, 6);
1436     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1437     hci_stack->le_scan_type = 0xff;
1438     hci_stack->le_connection_parameter_range.le_conn_interval_min = 0x0006;
1439     hci_stack->le_connection_parameter_range.le_conn_interval_max = 0x0C80;
1440     hci_stack->le_connection_parameter_range.le_conn_latency_min = 0x0000;
1441     hci_stack->le_connection_parameter_range.le_conn_latency_max = 0x03E8;
1442     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 0x000A;
1443     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 0x0C80;
1444 }
1445 
1446 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1447 
1448 #ifdef HAVE_MALLOC
1449     if (!hci_stack) {
1450         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1451     }
1452 #else
1453     hci_stack = &hci_stack_static;
1454 #endif
1455     memset(hci_stack, 0, sizeof(hci_stack_t));
1456 
1457     // reference to use transport layer implementation
1458     hci_stack->hci_transport = transport;
1459 
1460     // references to used control implementation
1461     hci_stack->control = control;
1462 
1463     // reference to used config
1464     hci_stack->config = config;
1465 
1466     // higher level handler
1467     hci_stack->packet_handler = dummy_handler;
1468 
1469     // store and open remote device db
1470     hci_stack->remote_device_db = remote_device_db;
1471     if (hci_stack->remote_device_db) {
1472         hci_stack->remote_device_db->open();
1473     }
1474 
1475     // max acl payload size defined in config.h
1476     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1477 
1478     // register packet handlers with transport
1479     transport->register_packet_handler(&packet_handler);
1480 
1481     hci_stack->state = HCI_STATE_OFF;
1482 
1483     // class of device
1484     hci_stack->class_of_device = 0x007a020c; // Smartphone
1485 
1486     // bondable by default
1487     hci_stack->bondable = 1;
1488 
1489     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1490     hci_stack->ssp_enable = 1;
1491     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1492     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1493     hci_stack->ssp_auto_accept = 1;
1494 
1495     hci_state_reset();
1496 }
1497 
1498 void hci_close(){
1499     // close remote device db
1500     if (hci_stack->remote_device_db) {
1501         hci_stack->remote_device_db->close();
1502     }
1503     while (hci_stack->connections) {
1504         // cancel all l2cap connections
1505         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1506         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1507     }
1508     hci_power_control(HCI_POWER_OFF);
1509 
1510 #ifdef HAVE_MALLOC
1511     free(hci_stack);
1512 #endif
1513     hci_stack = NULL;
1514 }
1515 
1516 void hci_set_class_of_device(uint32_t class_of_device){
1517     hci_stack->class_of_device = class_of_device;
1518 }
1519 
1520 void hci_disable_l2cap_timeout_check(){
1521     disable_l2cap_timeouts = 1;
1522 }
1523 // State-Module-Driver overview
1524 // state                    module  low-level
1525 // HCI_STATE_OFF             off      close
1526 // HCI_STATE_INITIALIZING,   on       open
1527 // HCI_STATE_WORKING,        on       open
1528 // HCI_STATE_HALTING,        on       open
1529 // HCI_STATE_SLEEPING,    off/sleep   close
1530 // HCI_STATE_FALLING_ASLEEP  on       open
1531 
1532 static int hci_power_control_on(void){
1533 
1534     // power on
1535     int err = 0;
1536     if (hci_stack->control && hci_stack->control->on){
1537         err = (*hci_stack->control->on)(hci_stack->config);
1538     }
1539     if (err){
1540         log_error( "POWER_ON failed");
1541         hci_emit_hci_open_failed();
1542         return err;
1543     }
1544 
1545     // open low-level device
1546     err = hci_stack->hci_transport->open(hci_stack->config);
1547     if (err){
1548         log_error( "HCI_INIT failed, turning Bluetooth off again");
1549         if (hci_stack->control && hci_stack->control->off){
1550             (*hci_stack->control->off)(hci_stack->config);
1551         }
1552         hci_emit_hci_open_failed();
1553         return err;
1554     }
1555     return 0;
1556 }
1557 
1558 static void hci_power_control_off(void){
1559 
1560     log_info("hci_power_control_off");
1561 
1562     // close low-level device
1563     hci_stack->hci_transport->close(hci_stack->config);
1564 
1565     log_info("hci_power_control_off - hci_transport closed");
1566 
1567     // power off
1568     if (hci_stack->control && hci_stack->control->off){
1569         (*hci_stack->control->off)(hci_stack->config);
1570     }
1571 
1572     log_info("hci_power_control_off - control closed");
1573 
1574     hci_stack->state = HCI_STATE_OFF;
1575 }
1576 
1577 static void hci_power_control_sleep(void){
1578 
1579     log_info("hci_power_control_sleep");
1580 
1581 #if 0
1582     // don't close serial port during sleep
1583 
1584     // close low-level device
1585     hci_stack->hci_transport->close(hci_stack->config);
1586 #endif
1587 
1588     // sleep mode
1589     if (hci_stack->control && hci_stack->control->sleep){
1590         (*hci_stack->control->sleep)(hci_stack->config);
1591     }
1592 
1593     hci_stack->state = HCI_STATE_SLEEPING;
1594 }
1595 
1596 static int hci_power_control_wake(void){
1597 
1598     log_info("hci_power_control_wake");
1599 
1600     // wake on
1601     if (hci_stack->control && hci_stack->control->wake){
1602         (*hci_stack->control->wake)(hci_stack->config);
1603     }
1604 
1605 #if 0
1606     // open low-level device
1607     int err = hci_stack->hci_transport->open(hci_stack->config);
1608     if (err){
1609         log_error( "HCI_INIT failed, turning Bluetooth off again");
1610         if (hci_stack->control && hci_stack->control->off){
1611             (*hci_stack->control->off)(hci_stack->config);
1612         }
1613         hci_emit_hci_open_failed();
1614         return err;
1615     }
1616 #endif
1617 
1618     return 0;
1619 }
1620 
1621 static void hci_power_transition_to_initializing(void){
1622     // set up state machine
1623     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1624     hci_stack->hci_packet_buffer_reserved = 0;
1625     hci_stack->state = HCI_STATE_INITIALIZING;
1626     hci_stack->substate = 0;
1627 }
1628 
1629 int hci_power_control(HCI_POWER_MODE power_mode){
1630 
1631     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1632 
1633     int err = 0;
1634     switch (hci_stack->state){
1635 
1636         case HCI_STATE_OFF:
1637             switch (power_mode){
1638                 case HCI_POWER_ON:
1639                     err = hci_power_control_on();
1640                     if (err) {
1641                         log_error("hci_power_control_on() error %u", err);
1642                         return err;
1643                     }
1644                     hci_power_transition_to_initializing();
1645                     break;
1646                 case HCI_POWER_OFF:
1647                     // do nothing
1648                     break;
1649                 case HCI_POWER_SLEEP:
1650                     // do nothing (with SLEEP == OFF)
1651                     break;
1652             }
1653             break;
1654 
1655         case HCI_STATE_INITIALIZING:
1656             switch (power_mode){
1657                 case HCI_POWER_ON:
1658                     // do nothing
1659                     break;
1660                 case HCI_POWER_OFF:
1661                     // no connections yet, just turn it off
1662                     hci_power_control_off();
1663                     break;
1664                 case HCI_POWER_SLEEP:
1665                     // no connections yet, just turn it off
1666                     hci_power_control_sleep();
1667                     break;
1668             }
1669             break;
1670 
1671         case HCI_STATE_WORKING:
1672             switch (power_mode){
1673                 case HCI_POWER_ON:
1674                     // do nothing
1675                     break;
1676                 case HCI_POWER_OFF:
1677                     // see hci_run
1678                     hci_stack->state = HCI_STATE_HALTING;
1679                     break;
1680                 case HCI_POWER_SLEEP:
1681                     // see hci_run
1682                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1683                     hci_stack->substate = 0;
1684                     break;
1685             }
1686             break;
1687 
1688         case HCI_STATE_HALTING:
1689             switch (power_mode){
1690                 case HCI_POWER_ON:
1691                     hci_power_transition_to_initializing();
1692                     break;
1693                 case HCI_POWER_OFF:
1694                     // do nothing
1695                     break;
1696                 case HCI_POWER_SLEEP:
1697                     // see hci_run
1698                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1699                     hci_stack->substate = 0;
1700                     break;
1701             }
1702             break;
1703 
1704         case HCI_STATE_FALLING_ASLEEP:
1705             switch (power_mode){
1706                 case HCI_POWER_ON:
1707 
1708 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1709                     // nothing to do, if H4 supports power management
1710                     if (bt_control_iphone_power_management_enabled()){
1711                         hci_stack->state = HCI_STATE_INITIALIZING;
1712                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1713                         break;
1714                     }
1715 #endif
1716                     hci_power_transition_to_initializing();
1717                     break;
1718                 case HCI_POWER_OFF:
1719                     // see hci_run
1720                     hci_stack->state = HCI_STATE_HALTING;
1721                     break;
1722                 case HCI_POWER_SLEEP:
1723                     // do nothing
1724                     break;
1725             }
1726             break;
1727 
1728         case HCI_STATE_SLEEPING:
1729             switch (power_mode){
1730                 case HCI_POWER_ON:
1731 
1732 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1733                     // nothing to do, if H4 supports power management
1734                     if (bt_control_iphone_power_management_enabled()){
1735                         hci_stack->state = HCI_STATE_INITIALIZING;
1736                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1737                         hci_update_scan_enable();
1738                         break;
1739                     }
1740 #endif
1741                     err = hci_power_control_wake();
1742                     if (err) return err;
1743                     hci_power_transition_to_initializing();
1744                     break;
1745                 case HCI_POWER_OFF:
1746                     hci_stack->state = HCI_STATE_HALTING;
1747                     break;
1748                 case HCI_POWER_SLEEP:
1749                     // do nothing
1750                     break;
1751             }
1752             break;
1753     }
1754 
1755     // create internal event
1756 	hci_emit_state();
1757 
1758 	// trigger next/first action
1759 	hci_run();
1760 
1761     return 0;
1762 }
1763 
1764 static void hci_update_scan_enable(void){
1765     // 2 = page scan, 1 = inq scan
1766     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1767     hci_run();
1768 }
1769 
1770 void hci_discoverable_control(uint8_t enable){
1771     if (enable) enable = 1; // normalize argument
1772 
1773     if (hci_stack->discoverable == enable){
1774         hci_emit_discoverable_enabled(hci_stack->discoverable);
1775         return;
1776     }
1777 
1778     hci_stack->discoverable = enable;
1779     hci_update_scan_enable();
1780 }
1781 
1782 void hci_connectable_control(uint8_t enable){
1783     if (enable) enable = 1; // normalize argument
1784 
1785     // don't emit event
1786     if (hci_stack->connectable == enable) return;
1787 
1788     hci_stack->connectable = enable;
1789     hci_update_scan_enable();
1790 }
1791 
1792 bd_addr_t * hci_local_bd_addr(void){
1793     return &hci_stack->local_bd_addr;
1794 }
1795 
1796 void hci_run(){
1797 
1798     hci_connection_t * connection;
1799     linked_item_t * it;
1800 
1801     // send continuation fragments first, as they block the prepared packet buffer
1802     if (hci_stack->acl_fragmentation_total_size > 0) {
1803         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1804         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1805             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1806             if (connection) {
1807                 hci_send_acl_packet_fragments(connection);
1808                 return;
1809             }
1810             // connection gone -> discard further fragments
1811             hci_stack->acl_fragmentation_total_size = 0;
1812             hci_stack->acl_fragmentation_pos = 0;
1813         }
1814     }
1815 
1816     if (!hci_can_send_command_packet_now()) return;
1817 
1818     // global/non-connection oriented commands
1819 
1820     // decline incoming connections
1821     if (hci_stack->decline_reason){
1822         uint8_t reason = hci_stack->decline_reason;
1823         hci_stack->decline_reason = 0;
1824         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1825         return;
1826     }
1827 
1828     // send scan enable
1829     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1830         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1831         hci_stack->new_scan_enable_value = 0xff;
1832         return;
1833     }
1834 
1835 #ifdef HAVE_BLE
1836     // handle le scan
1837     if (hci_stack->state == HCI_STATE_WORKING){
1838         switch(hci_stack->le_scanning_state){
1839             case LE_START_SCAN:
1840                 hci_stack->le_scanning_state = LE_SCANNING;
1841                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1842                 return;
1843 
1844             case LE_STOP_SCAN:
1845                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1846                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1847                 return;
1848             default:
1849                 break;
1850         }
1851         if (hci_stack->le_scan_type != 0xff){
1852             // defaults: active scanning, accept all advertisement packets
1853             int scan_type = hci_stack->le_scan_type;
1854             hci_stack->le_scan_type = 0xff;
1855             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0);
1856             return;
1857         }
1858     }
1859 #endif
1860 
1861     // send pending HCI commands
1862     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1863         connection = (hci_connection_t *) it;
1864 
1865         switch(connection->state){
1866             case SEND_CREATE_CONNECTION:
1867                 switch(connection->address_type){
1868                     case BD_ADDR_TYPE_CLASSIC:
1869                         log_info("sending hci_create_connection");
1870                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1871                         break;
1872                     default:
1873 #ifdef HAVE_BLE
1874                         log_info("sending hci_le_create_connection");
1875                         hci_send_cmd(&hci_le_create_connection,
1876                                      0x0060,    // scan interval: 60 ms
1877                                      0x0030,    // scan interval: 30 ms
1878                                      0,         // don't use whitelist
1879                                      connection->address_type, // peer address type
1880                                      connection->address,      // peer bd addr
1881                                      hci_stack->adv_addr_type, // our addr type:
1882                                      0x0008,    // conn interval min
1883                                      0x0018,    // conn interval max
1884                                      0,         // conn latency
1885                                      0x0048,    // supervision timeout
1886                                      0x0001,    // min ce length
1887                                      0x0001     // max ce length
1888                                      );
1889 
1890                         connection->state = SENT_CREATE_CONNECTION;
1891 #endif
1892                         break;
1893                 }
1894                 return;
1895 
1896             case RECEIVED_CONNECTION_REQUEST:
1897                 log_info("sending hci_accept_connection_request");
1898                 connection->state = ACCEPTED_CONNECTION_REQUEST;
1899                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1900                 return;
1901 
1902 #ifdef HAVE_BLE
1903             case SEND_CANCEL_CONNECTION:
1904                 connection->state = SENT_CANCEL_CONNECTION;
1905                 hci_send_cmd(&hci_le_create_connection_cancel);
1906                 return;
1907 #endif
1908             case SEND_DISCONNECT:
1909                 connection->state = SENT_DISCONNECT;
1910                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1911                 return;
1912 
1913             default:
1914                 break;
1915         }
1916 
1917         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1918             log_info("responding to link key request");
1919             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1920             link_key_t link_key;
1921             link_key_type_t link_key_type;
1922             if ( hci_stack->remote_device_db
1923               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1924               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1925                connection->link_key_type = link_key_type;
1926                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1927             } else {
1928                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1929             }
1930             return;
1931         }
1932 
1933         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1934             log_info("denying to pin request");
1935             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1936             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1937             return;
1938         }
1939 
1940         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1941             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1942             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1943             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1944                 // tweak authentication requirements
1945                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1946                 if (connection->bonding_flags & BONDING_DEDICATED){
1947                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1948                 }
1949                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1950                     authreq |= 1;
1951                 }
1952                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1953             } else {
1954                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1955             }
1956             return;
1957         }
1958 
1959         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1960             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1961             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1962             return;
1963         }
1964 
1965         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1966             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1967             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1968             return;
1969         }
1970 
1971         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1972             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1973             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1974             return;
1975         }
1976 
1977         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1978             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1979             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1980             return;
1981         }
1982         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1983             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1984             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
1985             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1986             return;
1987         }
1988         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1989             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1990             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1991             return;
1992         }
1993         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1994             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1995             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1996             return;
1997         }
1998 
1999 #ifdef HAVE_BLE
2000         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2001             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2002 
2003             uint16_t connection_interval_min = connection->le_conn_interval_min;
2004             connection->le_conn_interval_min = 0;
2005             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2006                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2007                 0x0000, 0xffff);
2008         }
2009 #endif
2010     }
2011 
2012     switch (hci_stack->state){
2013         case HCI_STATE_INITIALIZING:
2014             hci_initializing_state_machine();
2015             break;
2016 
2017         case HCI_STATE_HALTING:
2018 
2019             log_info("HCI_STATE_HALTING");
2020             // close all open connections
2021             connection =  (hci_connection_t *) hci_stack->connections;
2022             if (connection){
2023 
2024                 // send disconnect
2025                 if (!hci_can_send_command_packet_now()) return;
2026 
2027                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2028                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2029 
2030                 // send disconnected event right away - causes higher layer connections to get closed, too.
2031                 hci_shutdown_connection(connection);
2032                 return;
2033             }
2034             log_info("HCI_STATE_HALTING, calling off");
2035 
2036             // switch mode
2037             hci_power_control_off();
2038 
2039             log_info("HCI_STATE_HALTING, emitting state");
2040             hci_emit_state();
2041             log_info("HCI_STATE_HALTING, done");
2042             break;
2043 
2044         case HCI_STATE_FALLING_ASLEEP:
2045             switch(hci_stack->substate) {
2046                 case 0:
2047                     log_info("HCI_STATE_FALLING_ASLEEP");
2048                     // close all open connections
2049                     connection =  (hci_connection_t *) hci_stack->connections;
2050 
2051 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2052                     // don't close connections, if H4 supports power management
2053                     if (bt_control_iphone_power_management_enabled()){
2054                         connection = NULL;
2055                     }
2056 #endif
2057                     if (connection){
2058 
2059                         // send disconnect
2060                         if (!hci_can_send_command_packet_now()) return;
2061 
2062                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2063                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2064 
2065                         // send disconnected event right away - causes higher layer connections to get closed, too.
2066                         hci_shutdown_connection(connection);
2067                         return;
2068                     }
2069 
2070                     if (hci_classic_supported()){
2071                         // disable page and inquiry scan
2072                         if (!hci_can_send_command_packet_now()) return;
2073 
2074                         log_info("HCI_STATE_HALTING, disabling inq scans");
2075                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
2076 
2077                         // continue in next sub state
2078                         hci_stack->substate++;
2079                         break;
2080                     }
2081                     // fall through for ble-only chips
2082 
2083                 case 2:
2084                     log_info("HCI_STATE_HALTING, calling sleep");
2085 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2086                     // don't actually go to sleep, if H4 supports power management
2087                     if (bt_control_iphone_power_management_enabled()){
2088                         // SLEEP MODE reached
2089                         hci_stack->state = HCI_STATE_SLEEPING;
2090                         hci_emit_state();
2091                         break;
2092                     }
2093 #endif
2094                     // switch mode
2095                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2096                     hci_emit_state();
2097                     break;
2098 
2099                 default:
2100                     break;
2101             }
2102             break;
2103 
2104         default:
2105             break;
2106     }
2107 }
2108 
2109 int hci_send_cmd_packet(uint8_t *packet, int size){
2110     bd_addr_t addr;
2111     hci_connection_t * conn;
2112     // house-keeping
2113 
2114     // create_connection?
2115     if (IS_COMMAND(packet, hci_create_connection)){
2116         bt_flip_addr(addr, &packet[3]);
2117         log_info("Create_connection to %s", bd_addr_to_str(addr));
2118 
2119         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2120         if (!conn){
2121             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2122             if (!conn){
2123                 // notify client that alloc failed
2124                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2125                 return 0; // don't sent packet to controller
2126             }
2127             conn->state = SEND_CREATE_CONNECTION;
2128         }
2129         log_info("conn state %u", conn->state);
2130         switch (conn->state){
2131             // if connection active exists
2132             case OPEN:
2133                 // and OPEN, emit connection complete command, don't send to controller
2134                 hci_emit_connection_complete(conn, 0);
2135                 return 0;
2136             case SEND_CREATE_CONNECTION:
2137                 // connection created by hci, e.g. dedicated bonding
2138                 break;
2139             default:
2140                 // otherwise, just ignore as it is already in the open process
2141                 return 0;
2142         }
2143         conn->state = SENT_CREATE_CONNECTION;
2144     }
2145 
2146     if (IS_COMMAND(packet, hci_link_key_request_reply)){
2147         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
2148     }
2149     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
2150         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
2151     }
2152 
2153     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2154         if (hci_stack->remote_device_db){
2155             bt_flip_addr(addr, &packet[3]);
2156             hci_stack->remote_device_db->delete_link_key(&addr);
2157         }
2158     }
2159 
2160     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2161     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2162         bt_flip_addr(addr, &packet[3]);
2163         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2164         if (conn){
2165             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2166         }
2167     }
2168 
2169     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2170     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2171     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2172     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2173         bt_flip_addr(addr, &packet[3]);
2174         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2175         if (conn){
2176             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2177         }
2178     }
2179 
2180 #ifdef HAVE_BLE
2181     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2182         hci_stack->adv_addr_type = packet[8];
2183     }
2184     if (IS_COMMAND(packet, hci_le_set_random_address)){
2185         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2186     }
2187 #endif
2188 
2189     hci_stack->num_cmd_packets--;
2190 
2191     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2192     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2193 
2194     // release packet buffer for synchronous transport implementations
2195     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2196         hci_stack->hci_packet_buffer_reserved = 0;
2197     }
2198 
2199     return err;
2200 }
2201 
2202 // disconnect because of security block
2203 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2204     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2205     if (!connection) return;
2206     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2207 }
2208 
2209 
2210 // Configure Secure Simple Pairing
2211 
2212 // enable will enable SSP during init
2213 void hci_ssp_set_enable(int enable){
2214     hci_stack->ssp_enable = enable;
2215 }
2216 
2217 int hci_local_ssp_activated(){
2218     return hci_ssp_supported() && hci_stack->ssp_enable;
2219 }
2220 
2221 // if set, BTstack will respond to io capability request using authentication requirement
2222 void hci_ssp_set_io_capability(int io_capability){
2223     hci_stack->ssp_io_capability = io_capability;
2224 }
2225 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2226     hci_stack->ssp_authentication_requirement = authentication_requirement;
2227 }
2228 
2229 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2230 void hci_ssp_set_auto_accept(int auto_accept){
2231     hci_stack->ssp_auto_accept = auto_accept;
2232 }
2233 
2234 /**
2235  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2236  */
2237 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2238 
2239     if (!hci_can_send_command_packet_now()){
2240         log_error("hci_send_cmd called but cannot send packet now");
2241         return 0;
2242     }
2243 
2244     // for HCI INITIALIZATION
2245     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2246     hci_stack->last_cmd_opcode = cmd->opcode;
2247 
2248     hci_reserve_packet_buffer();
2249     uint8_t * packet = hci_stack->hci_packet_buffer;
2250 
2251     va_list argptr;
2252     va_start(argptr, cmd);
2253     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
2254     va_end(argptr);
2255 
2256     return hci_send_cmd_packet(packet, size);
2257 }
2258 
2259 // Create various non-HCI events.
2260 // TODO: generalize, use table similar to hci_create_command
2261 
2262 void hci_emit_state(){
2263     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2264     uint8_t event[3];
2265     event[0] = BTSTACK_EVENT_STATE;
2266     event[1] = sizeof(event) - 2;
2267     event[2] = hci_stack->state;
2268     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2269     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2270 }
2271 
2272 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2273     uint8_t event[13];
2274     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2275     event[1] = sizeof(event) - 2;
2276     event[2] = status;
2277     bt_store_16(event, 3, conn->con_handle);
2278     bt_flip_addr(&event[5], conn->address);
2279     event[11] = 1; // ACL connection
2280     event[12] = 0; // encryption disabled
2281     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2282     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2283 }
2284 
2285 void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t * address, uint16_t conn_handle, uint8_t status){
2286     uint8_t event[21];
2287     event[0] = HCI_EVENT_LE_META;
2288     event[1] = sizeof(event) - 2;
2289     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2290     event[3] = status;
2291     bt_store_16(event, 4, conn_handle);
2292     event[6] = 0; // TODO: role
2293     event[7] = address_type;
2294     bt_flip_addr(&event[8], *address);
2295     bt_store_16(event, 14, 0); // interval
2296     bt_store_16(event, 16, 0); // latency
2297     bt_store_16(event, 18, 0); // supervision timeout
2298     event[20] = 0; // master clock accuracy
2299     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2300     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2301 }
2302 
2303 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2304     uint8_t event[6];
2305     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2306     event[1] = sizeof(event) - 2;
2307     event[2] = 0; // status = OK
2308     bt_store_16(event, 3, handle);
2309     event[5] = reason;
2310     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2311     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2312 }
2313 
2314 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2315     if (disable_l2cap_timeouts) return;
2316     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2317     uint8_t event[4];
2318     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2319     event[1] = sizeof(event) - 2;
2320     bt_store_16(event, 2, conn->con_handle);
2321     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2322     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2323 }
2324 
2325 void hci_emit_nr_connections_changed(){
2326     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2327     uint8_t event[3];
2328     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2329     event[1] = sizeof(event) - 2;
2330     event[2] = nr_hci_connections();
2331     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2332     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2333 }
2334 
2335 void hci_emit_hci_open_failed(){
2336     log_info("BTSTACK_EVENT_POWERON_FAILED");
2337     uint8_t event[2];
2338     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2339     event[1] = sizeof(event) - 2;
2340     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2341     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2342 }
2343 
2344 #ifndef EMBEDDED
2345 void hci_emit_btstack_version() {
2346     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2347     uint8_t event[6];
2348     event[0] = BTSTACK_EVENT_VERSION;
2349     event[1] = sizeof(event) - 2;
2350     event[2] = BTSTACK_MAJOR;
2351     event[3] = BTSTACK_MINOR;
2352     bt_store_16(event, 4, BTSTACK_REVISION);
2353     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2354     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2355 }
2356 #endif
2357 
2358 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2359     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2360     uint8_t event[3];
2361     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2362     event[1] = sizeof(event) - 2;
2363     event[2] = enabled;
2364     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2365     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2366 }
2367 
2368 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2369     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2370     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2371     event[1] = sizeof(event) - 2 - 1;
2372     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
2373     bt_flip_addr(&event[3], *addr);
2374     memcpy(&event[9], name, 248);
2375 
2376     event[9+248] = 0;   // assert \0 for log_info
2377     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2378 
2379     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2380     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2381 }
2382 
2383 void hci_emit_discoverable_enabled(uint8_t enabled){
2384     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2385     uint8_t event[3];
2386     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2387     event[1] = sizeof(event) - 2;
2388     event[2] = enabled;
2389     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2390     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2391 }
2392 
2393 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2394     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2395     uint8_t event[5];
2396     int pos = 0;
2397     event[pos++] = GAP_SECURITY_LEVEL;
2398     event[pos++] = sizeof(event) - 2;
2399     bt_store_16(event, 2, con_handle);
2400     pos += 2;
2401     event[pos++] = level;
2402     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2403     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2404 }
2405 
2406 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2407     log_info("hci_emit_dedicated_bonding_result %u ", status);
2408     uint8_t event[9];
2409     int pos = 0;
2410     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2411     event[pos++] = sizeof(event) - 2;
2412     event[pos++] = status;
2413     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2414     pos += 6;
2415     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2416     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2417 }
2418 
2419 // query if remote side supports SSP
2420 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2421     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2422     if (!connection) return 0;
2423     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2424 }
2425 
2426 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2427     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2428 }
2429 
2430 // GAP API
2431 /**
2432  * @bbrief enable/disable bonding. default is enabled
2433  * @praram enabled
2434  */
2435 void gap_set_bondable_mode(int enable){
2436     hci_stack->bondable = enable ? 1 : 0;
2437 }
2438 
2439 /**
2440  * @brief map link keys to security levels
2441  */
2442 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2443     switch (link_key_type){
2444         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2445             return LEVEL_4;
2446         case COMBINATION_KEY:
2447         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2448             return LEVEL_3;
2449         default:
2450             return LEVEL_2;
2451     }
2452 }
2453 
2454 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2455     if (!connection) return LEVEL_0;
2456     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2457     return gap_security_level_for_link_key_type(connection->link_key_type);
2458 }
2459 
2460 
2461 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2462     log_info("gap_mitm_protection_required_for_security_level %u", level);
2463     return level > LEVEL_2;
2464 }
2465 
2466 /**
2467  * @brief get current security level
2468  */
2469 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2470     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2471     if (!connection) return LEVEL_0;
2472     return gap_security_level_for_connection(connection);
2473 }
2474 
2475 /**
2476  * @brief request connection to device to
2477  * @result GAP_AUTHENTICATION_RESULT
2478  */
2479 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2480     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2481     if (!connection){
2482         hci_emit_security_level(con_handle, LEVEL_0);
2483         return;
2484     }
2485     gap_security_level_t current_level = gap_security_level(con_handle);
2486     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2487     if (current_level >= requested_level){
2488         hci_emit_security_level(con_handle, current_level);
2489         return;
2490     }
2491 
2492     connection->requested_security_level = requested_level;
2493 
2494 #if 0
2495     // sending encryption request without a link key results in an error.
2496     // TODO: figure out how to use it properly
2497 
2498     // would enabling ecnryption suffice (>= LEVEL_2)?
2499     if (hci_stack->remote_device_db){
2500         link_key_type_t link_key_type;
2501         link_key_t      link_key;
2502         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2503             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2504                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2505                 return;
2506             }
2507         }
2508     }
2509 #endif
2510 
2511     // try to authenticate connection
2512     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2513     hci_run();
2514 }
2515 
2516 /**
2517  * @brief start dedicated bonding with device. disconnect after bonding
2518  * @param device
2519  * @param request MITM protection
2520  * @result GAP_DEDICATED_BONDING_COMPLETE
2521  */
2522 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2523 
2524     // create connection state machine
2525     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2526 
2527     if (!connection){
2528         return BTSTACK_MEMORY_ALLOC_FAILED;
2529     }
2530 
2531     // delete linkn key
2532     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2533 
2534     // configure LEVEL_2/3, dedicated bonding
2535     connection->state = SEND_CREATE_CONNECTION;
2536     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2537     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2538     connection->bonding_flags = BONDING_DEDICATED;
2539 
2540     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2541 
2542     // handle: connnection failure (connection complete != ok)
2543     // handle: authentication failure
2544     // handle: disconnect on done
2545 
2546     hci_run();
2547 
2548     return 0;
2549 }
2550 
2551 void gap_set_local_name(const char * local_name){
2552     hci_stack->local_name = local_name;
2553 }
2554 
2555 le_command_status_t le_central_start_scan(){
2556     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2557     hci_stack->le_scanning_state = LE_START_SCAN;
2558     hci_run();
2559     return BLE_PERIPHERAL_OK;
2560 }
2561 
2562 le_command_status_t le_central_stop_scan(){
2563     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2564     hci_stack->le_scanning_state = LE_STOP_SCAN;
2565     hci_run();
2566     return BLE_PERIPHERAL_OK;
2567 }
2568 
2569 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2570     hci_stack->le_scan_type     = scan_type;
2571     hci_stack->le_scan_interval = scan_interval;
2572     hci_stack->le_scan_window   = scan_window;
2573     hci_run();
2574 }
2575 
2576 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2577     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2578     if (!conn){
2579         log_info("le_central_connect: no connection exists yet, creating context");
2580         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2581         if (!conn){
2582             // notify client that alloc failed
2583             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
2584             log_info("le_central_connect: failed to alloc hci_connection_t");
2585             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2586         }
2587         conn->state = SEND_CREATE_CONNECTION;
2588         log_info("le_central_connect: send create connection next");
2589         hci_run();
2590         return BLE_PERIPHERAL_OK;
2591     }
2592 
2593     if (!hci_is_le_connection(conn) ||
2594         conn->state == SEND_CREATE_CONNECTION ||
2595         conn->state == SENT_CREATE_CONNECTION) {
2596         hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
2597         log_error("le_central_connect: classic connection or connect is already being created");
2598         return BLE_PERIPHERAL_IN_WRONG_STATE;
2599     }
2600 
2601     log_info("le_central_connect: context exists with state %u", conn->state);
2602     hci_emit_le_connection_complete(conn->address_type, &conn->address, conn->con_handle, 0);
2603     hci_run();
2604     return BLE_PERIPHERAL_OK;
2605 }
2606 
2607 // @assumption: only a single outgoing LE Connection exists
2608 static hci_connection_t * le_central_get_outgoing_connection(){
2609     linked_item_t *it;
2610     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
2611         hci_connection_t * conn = (hci_connection_t *) it;
2612         if (!hci_is_le_connection(conn)) continue;
2613         switch (conn->state){
2614             case SEND_CREATE_CONNECTION:
2615             case SENT_CREATE_CONNECTION:
2616                 return conn;
2617             default:
2618                 break;
2619         };
2620     }
2621     return NULL;
2622 }
2623 
2624 le_command_status_t le_central_connect_cancel(){
2625     hci_connection_t * conn = le_central_get_outgoing_connection();
2626     switch (conn->state){
2627         case SEND_CREATE_CONNECTION:
2628             // skip sending create connection and emit event instead
2629             hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2630             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2631             btstack_memory_hci_connection_free( conn );
2632             break;
2633         case SENT_CREATE_CONNECTION:
2634             // request to send cancel connection
2635             conn->state = SEND_CANCEL_CONNECTION;
2636             hci_run();
2637             break;
2638         default:
2639             break;
2640     }
2641     return BLE_PERIPHERAL_OK;
2642 }
2643 
2644 /**
2645  * @brief Updates the connection parameters for a given LE connection
2646  * @param handle
2647  * @param conn_interval_min (unit: 1.25ms)
2648  * @param conn_interval_max (unit: 1.25ms)
2649  * @param conn_latency
2650  * @param supervision_timeout (unit: 10ms)
2651  * @returns 0 if ok
2652  */
2653 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2654     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2655     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2656     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2657     connection->le_conn_interval_min = conn_interval_min;
2658     connection->le_conn_interval_max = conn_interval_max;
2659     connection->le_conn_latency = conn_latency;
2660     connection->le_supervision_timeout = supervision_timeout;
2661     return 0;
2662 }
2663 
2664 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2665     hci_connection_t * conn = hci_connection_for_handle(handle);
2666     if (!conn){
2667         hci_emit_disconnection_complete(handle, 0);
2668         return BLE_PERIPHERAL_OK;
2669     }
2670     conn->state = SEND_DISCONNECT;
2671     hci_run();
2672     return BLE_PERIPHERAL_OK;
2673 }
2674 
2675 void hci_disconnect_all(){
2676     linked_list_iterator_t it;
2677     linked_list_iterator_init(&it, &hci_stack->connections);
2678     while (linked_list_iterator_has_next(&it)){
2679         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
2680         if (con->state == SENT_DISCONNECT) continue;
2681         con->state = SEND_DISCONNECT;
2682     }
2683     hci_run();
2684 }
2685