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