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