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