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