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