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