source: asp3_tinet_ecnl_arm/trunk/btstack/src/hci.c@ 352

Last change on this file since 352 was 352, checked in by coas-nagasima, 6 years ago

arm向けASP3版ECNLを追加

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