1 /* 2 * Copyright (C) 2014 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 24 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define __BTSTACK_FILE__ "daemon.c" 39 40 /* 41 * daemon.c 42 * 43 * Created by Matthias Ringwald on 7/1/09. 44 * 45 * BTstack background daemon 46 * 47 */ 48 49 #include "btstack_config.h" 50 51 #include <pthread.h> 52 #include <signal.h> 53 #include <stdio.h> 54 #include <stdlib.h> 55 #include <strings.h> 56 #include <unistd.h> 57 58 #ifdef _WIN32 59 #include "Winsock2.h" 60 #endif 61 62 #include <getopt.h> 63 64 #include "btstack.h" 65 #include "btstack_client.h" 66 #include "btstack_debug.h" 67 #include "btstack_device_name_db.h" 68 #include "btstack_event.h" 69 #include "btstack_linked_list.h" 70 #include "btstack_run_loop.h" 71 72 #ifdef _WIN32 73 #include "btstack_run_loop_windows.h" 74 #else 75 #include "btstack_run_loop_posix.h" 76 #endif 77 #include "btstack_version.h" 78 #include "classic/btstack_link_key_db.h" 79 #include "classic/rfcomm.h" 80 #include "classic/sdp_server.h" 81 #include "classic/sdp_client.h" 82 #include "classic/sdp_client_rfcomm.h" 83 #include "hci.h" 84 #include "hci_cmd.h" 85 #include "hci_dump.h" 86 #include "hci_transport.h" 87 #include "l2cap.h" 88 #include "rfcomm_service_db.h" 89 #include "socket_connection.h" 90 91 #ifdef ENABLE_BLE 92 #include "ble/gatt_client.h" 93 #include "ble/att_server.h" 94 #include "ble/att_db.h" 95 #include "ble/le_device_db.h" 96 #include "ble/sm.h" 97 #endif 98 99 #ifdef HAVE_PLATFORM_IPHONE_OS 100 #include <CoreFoundation/CoreFoundation.h> 101 #include <notify.h> 102 #include "../port/ios/src/btstack_control_iphone.h" 103 #include "../port/ios/src/platform_iphone.h" 104 // support for "enforece wake device" in h4 - used by iOS power management 105 extern void hci_transport_h4_iphone_set_enforce_wake_device(char *path); 106 #endif 107 108 // copy of prototypes 109 const btstack_device_name_db_t * btstack_device_name_db_corefoundation_instance(void); 110 const btstack_device_name_db_t * btstack_device_name_db_fs_instance(void); 111 const btstack_link_key_db_t * btstack_link_key_db_corefoundation_instance(void); 112 const btstack_link_key_db_t * btstack_link_key_db_fs_instance(void); 113 114 #ifndef BTSTACK_LOG_FILE 115 #define BTSTACK_LOG_FILE "/tmp/hci_dump.pklg" 116 #endif 117 118 // use logger: format HCI_DUMP_PACKETLOGGER, HCI_DUMP_BLUEZ or HCI_DUMP_STDOUT 119 #ifndef BTSTACK_LOG_TYPE 120 #define BTSTACK_LOG_TYPE HCI_DUMP_PACKETLOGGER 121 #endif 122 123 #define DAEMON_NO_ACTIVE_CLIENT_TIMEOUT 10000 124 125 #define ATT_MAX_LONG_ATTRIBUTE_SIZE 512 126 127 128 #define SERVICE_LENGTH 20 129 #define CHARACTERISTIC_LENGTH 24 130 #define CHARACTERISTIC_DESCRIPTOR_LENGTH 18 131 132 // ATT_MTU - 1 133 #define ATT_MAX_ATTRIBUTE_SIZE 22 134 135 // HCI CMD OGF/OCF 136 #define READ_CMD_OGF(buffer) (buffer[1] >> 2) 137 #define READ_CMD_OCF(buffer) ((buffer[1] & 0x03) << 8 | buffer[0]) 138 139 typedef struct { 140 // linked list - assert: first field 141 btstack_linked_item_t item; 142 143 // connection 144 connection_t * connection; 145 146 btstack_linked_list_t rfcomm_cids; 147 btstack_linked_list_t rfcomm_services; 148 btstack_linked_list_t l2cap_cids; 149 btstack_linked_list_t l2cap_psms; 150 btstack_linked_list_t sdp_record_handles; 151 btstack_linked_list_t gatt_con_handles; 152 // power mode 153 HCI_POWER_MODE power_mode; 154 155 // discoverable 156 uint8_t discoverable; 157 158 } client_state_t; 159 160 typedef struct btstack_linked_list_uint32 { 161 btstack_linked_item_t item; 162 uint32_t value; 163 } btstack_linked_list_uint32_t; 164 165 typedef struct btstack_linked_list_connection { 166 btstack_linked_item_t item; 167 connection_t * connection; 168 } btstack_linked_list_connection_t; 169 170 typedef struct btstack_linked_list_gatt_client_helper{ 171 btstack_linked_item_t item; 172 hci_con_handle_t con_handle; 173 connection_t * active_connection; // the one that started the current query 174 btstack_linked_list_t all_connections; // list of all connections that ever used this helper 175 uint16_t characteristic_length; 176 uint16_t characteristic_handle; 177 uint8_t characteristic_buffer[10 + ATT_MAX_LONG_ATTRIBUTE_SIZE]; // header for sending event right away 178 uint8_t long_query_type; 179 } btstack_linked_list_gatt_client_helper_t; 180 181 // MARK: prototypes 182 static void handle_sdp_rfcomm_service_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 183 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 184 #ifdef ENABLE_BLE 185 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size); 186 #endif 187 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state); 188 static client_state_t * client_for_connection(connection_t *connection); 189 static int clients_require_power_on(void); 190 static int clients_require_discoverable(void); 191 static void clients_clear_power_request(void); 192 static void start_power_off_timer(void); 193 static void stop_power_off_timer(void); 194 static client_state_t * client_for_connection(connection_t *connection); 195 static void hci_emit_system_bluetooth_enabled(uint8_t enabled); 196 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size); 197 198 199 // MARK: globals 200 201 #ifdef HAVE_TRANSPORT_H4 202 static hci_transport_config_uart_t hci_transport_config_uart; 203 #endif 204 205 static const hci_transport_t * transport; 206 static btstack_timer_source_t timeout; 207 static uint8_t timeout_active = 0; 208 static int power_management_sleep = 0; 209 static btstack_linked_list_t clients = NULL; // list of connected clients ` 210 #ifdef ENABLE_BLE 211 static btstack_linked_list_t gatt_client_helpers = NULL; // list of used gatt client (helpers) 212 #endif 213 214 static void (*bluetooth_status_handler)(BLUETOOTH_STATE state) = dummy_bluetooth_status_handler; 215 216 static btstack_packet_callback_registration_t hci_event_callback_registration; 217 218 static int global_enable = 0; 219 220 static btstack_link_key_db_t const * btstack_link_key_db = NULL; 221 static btstack_device_name_db_t const * btstack_device_name_db = NULL; 222 // static int rfcomm_channel_generator = 1; 223 224 static uint8_t attribute_value[1000]; 225 static const int attribute_value_buffer_size = sizeof(attribute_value); 226 static uint8_t serviceSearchPattern[200]; 227 static uint8_t attributeIDList[50]; 228 static void * sdp_client_query_connection; 229 230 static int loggingEnabled; 231 232 // stashed code from l2cap.c and rfcomm.c -- needed for new implementation 233 #if 0 234 static void l2cap_emit_credits(l2cap_channel_t *channel, uint8_t credits) { 235 236 log_info("DAEMON_EVENT_L2CAP_CREDITS local_cid 0x%x credits %u", channel->local_cid, credits); 237 238 uint8_t event[5]; 239 event[0] = DAEMON_EVENT_L2CAP_CREDITS; 240 event[1] = sizeof(event) - 2; 241 little_endian_store_16(event, 2, channel->local_cid); 242 event[4] = credits; 243 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 244 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 245 } 246 247 static void l2cap_hand_out_credits(void){ 248 btstack_linked_list_iterator_t it; 249 btstack_linked_list_iterator_init(&it, &l2cap_channels); 250 while (btstack_linked_list_iterator_has_next(&it)){ 251 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 252 if (channel->state != L2CAP_STATE_OPEN) continue; 253 if (!hci_number_free_acl_slots_for_handle(channel->handle)) return; 254 l2cap_emit_credits(channel, 1); 255 } 256 } 257 static void rfcomm_emit_credits(rfcomm_channel_t * channel, uint8_t credits) { 258 log_info("DAEMON_EVENT_RFCOMM_CREDITS cid 0x%02x credits %u", channel->rfcomm_cid, credits); 259 uint8_t event[5]; 260 event[0] = DAEMON_EVENT_RFCOMM_CREDITS; 261 event[1] = sizeof(event) - 2; 262 little_endian_store_16(event, 2, channel->rfcomm_cid); 263 event[4] = credits; 264 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 265 (*app_packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event)); 266 } 267 static void rfcomm_hand_out_credits(void){ 268 btstack_linked_item_t * it; 269 for (it = (btstack_linked_item_t *) rfcomm_channels; it ; it = it->next){ 270 rfcomm_channel_t * channel = (rfcomm_channel_t *) it; 271 if (channel->state != RFCOMM_CHANNEL_OPEN) { 272 // log_info("DAEMON_EVENT_RFCOMM_CREDITS: multiplexer not open"); 273 continue; 274 } 275 if (!channel->credits_outgoing) { 276 // log_info("DAEMON_EVENT_RFCOMM_CREDITS: no outgoing credits"); 277 continue; 278 } 279 // channel open, multiplexer has l2cap credits and we didn't hand out credit before -> go! 280 // log_info("DAEMON_EVENT_RFCOMM_CREDITS: 1"); 281 rfcomm_emit_credits(channel, 1); 282 } 283 } 284 285 #endif 286 287 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state){ 288 log_info("Bluetooth status: %u\n", state); 289 }; 290 291 static void daemon_no_connections_timeout(struct btstack_timer_source *ts){ 292 if (clients_require_power_on()) return; // false alarm :) 293 log_info("No active client connection for %u seconds -> POWER OFF\n", DAEMON_NO_ACTIVE_CLIENT_TIMEOUT/1000); 294 hci_power_control(HCI_POWER_OFF); 295 } 296 297 298 static void add_uint32_to_list(btstack_linked_list_t *list, uint32_t value){ 299 btstack_linked_list_iterator_t it; 300 btstack_linked_list_iterator_init(&it, list); 301 while (btstack_linked_list_iterator_has_next(&it)){ 302 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 303 if ( item->value == value) return; // already in list 304 } 305 306 btstack_linked_list_uint32_t * item = malloc(sizeof(btstack_linked_list_uint32_t)); 307 if (!item) return; 308 item->value = value; 309 btstack_linked_list_add(list, (btstack_linked_item_t *) item); 310 } 311 312 static void remove_and_free_uint32_from_list(btstack_linked_list_t *list, uint32_t value){ 313 btstack_linked_list_iterator_t it; 314 btstack_linked_list_iterator_init(&it, list); 315 while (btstack_linked_list_iterator_has_next(&it)){ 316 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 317 if ( item->value != value) continue; 318 btstack_linked_list_remove(list, (btstack_linked_item_t *) item); 319 free(item); 320 } 321 } 322 323 static void daemon_add_client_rfcomm_service(connection_t * connection, uint16_t service_channel){ 324 client_state_t * client_state = client_for_connection(connection); 325 if (!client_state) return; 326 add_uint32_to_list(&client_state->rfcomm_services, service_channel); 327 } 328 329 static void daemon_remove_client_rfcomm_service(connection_t * connection, uint16_t service_channel){ 330 client_state_t * client_state = client_for_connection(connection); 331 if (!client_state) return; 332 remove_and_free_uint32_from_list(&client_state->rfcomm_services, service_channel); 333 } 334 335 static void daemon_add_client_rfcomm_channel(connection_t * connection, uint16_t cid){ 336 client_state_t * client_state = client_for_connection(connection); 337 if (!client_state) return; 338 add_uint32_to_list(&client_state->rfcomm_cids, cid); 339 } 340 341 static void daemon_remove_client_rfcomm_channel(connection_t * connection, uint16_t cid){ 342 client_state_t * client_state = client_for_connection(connection); 343 if (!client_state) return; 344 remove_and_free_uint32_from_list(&client_state->rfcomm_cids, cid); 345 } 346 347 static void daemon_add_client_l2cap_service(connection_t * connection, uint16_t psm){ 348 client_state_t * client_state = client_for_connection(connection); 349 if (!client_state) return; 350 add_uint32_to_list(&client_state->l2cap_psms, psm); 351 } 352 353 static void daemon_remove_client_l2cap_service(connection_t * connection, uint16_t psm){ 354 client_state_t * client_state = client_for_connection(connection); 355 if (!client_state) return; 356 remove_and_free_uint32_from_list(&client_state->l2cap_psms, psm); 357 } 358 359 static void daemon_add_client_l2cap_channel(connection_t * connection, uint16_t cid){ 360 client_state_t * client_state = client_for_connection(connection); 361 if (!client_state) return; 362 add_uint32_to_list(&client_state->l2cap_cids, cid); 363 } 364 365 static void daemon_remove_client_l2cap_channel(connection_t * connection, uint16_t cid){ 366 client_state_t * client_state = client_for_connection(connection); 367 if (!client_state) return; 368 remove_and_free_uint32_from_list(&client_state->l2cap_cids, cid); 369 } 370 371 static void daemon_add_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){ 372 client_state_t * client_state = client_for_connection(connection); 373 if (!client_state) return; 374 add_uint32_to_list(&client_state->sdp_record_handles, handle); 375 } 376 377 static void daemon_remove_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){ 378 client_state_t * client_state = client_for_connection(connection); 379 if (!client_state) return; 380 remove_and_free_uint32_from_list(&client_state->sdp_record_handles, handle); 381 } 382 383 #ifdef ENABLE_BLE 384 static void daemon_add_gatt_client_handle(connection_t * connection, uint32_t handle){ 385 client_state_t * client_state = client_for_connection(connection); 386 if (!client_state) return; 387 388 // check if handle already exists in the gatt_con_handles list 389 btstack_linked_list_iterator_t it; 390 int handle_found = 0; 391 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 392 while (btstack_linked_list_iterator_has_next(&it)){ 393 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 394 if (item->value == handle){ 395 handle_found = 1; 396 break; 397 } 398 } 399 // if handle doesn't exist add it to gatt_con_handles 400 if (!handle_found){ 401 add_uint32_to_list(&client_state->gatt_con_handles, handle); 402 } 403 404 // check if there is a helper with given handle 405 btstack_linked_list_gatt_client_helper_t * gatt_helper = NULL; 406 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 407 while (btstack_linked_list_iterator_has_next(&it)){ 408 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 409 if (item->con_handle == handle){ 410 gatt_helper = item; 411 break; 412 } 413 } 414 415 // if gatt_helper doesn't exist, create it and add it to gatt_client_helpers list 416 if (!gatt_helper){ 417 gatt_helper = calloc(sizeof(btstack_linked_list_gatt_client_helper_t), 1); 418 if (!gatt_helper) return; 419 gatt_helper->con_handle = handle; 420 btstack_linked_list_add(&gatt_client_helpers, (btstack_linked_item_t *) gatt_helper); 421 } 422 423 // check if connection exists 424 int connection_found = 0; 425 btstack_linked_list_iterator_init(&it, &gatt_helper->all_connections); 426 while (btstack_linked_list_iterator_has_next(&it)){ 427 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 428 if (item->connection == connection){ 429 connection_found = 1; 430 break; 431 } 432 } 433 434 // if connection is not found, add it to the all_connections, and set it as active connection 435 if (!connection_found){ 436 btstack_linked_list_connection_t * con = calloc(sizeof(btstack_linked_list_connection_t), 1); 437 if (!con) return; 438 con->connection = connection; 439 btstack_linked_list_add(&gatt_helper->all_connections, (btstack_linked_item_t *)con); 440 } 441 } 442 443 444 static void daemon_remove_gatt_client_handle(connection_t * connection, uint32_t handle){ 445 // PART 1 - uses connection & handle 446 // might be extracted or vanish totally 447 client_state_t * client_state = client_for_connection(connection); 448 if (!client_state) return; 449 450 btstack_linked_list_iterator_t it; 451 // remove handle from gatt_con_handles list 452 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 453 while (btstack_linked_list_iterator_has_next(&it)){ 454 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 455 if (item->value == handle){ 456 btstack_linked_list_remove(&client_state->gatt_con_handles, (btstack_linked_item_t *) item); 457 free(item); 458 } 459 } 460 461 // PART 2 - only uses handle 462 463 // find helper with given handle 464 btstack_linked_list_gatt_client_helper_t * helper = NULL; 465 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 466 while (btstack_linked_list_iterator_has_next(&it)){ 467 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 468 if (item->con_handle == handle){ 469 helper = item; 470 break; 471 } 472 } 473 474 if (!helper) return; 475 // remove connection from helper 476 btstack_linked_list_iterator_init(&it, &helper->all_connections); 477 while (btstack_linked_list_iterator_has_next(&it)){ 478 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 479 if (item->connection == connection){ 480 btstack_linked_list_remove(&helper->all_connections, (btstack_linked_item_t *) item); 481 free(item); 482 break; 483 } 484 } 485 486 if (helper->active_connection == connection){ 487 helper->active_connection = NULL; 488 } 489 // if helper has no more connections, call disconnect 490 if (helper->all_connections == NULL){ 491 gap_disconnect((hci_con_handle_t) helper->con_handle); 492 } 493 } 494 495 496 static void daemon_remove_gatt_client_helper(uint32_t con_handle){ 497 btstack_linked_list_iterator_t it, cl; 498 // find helper with given handle 499 btstack_linked_list_gatt_client_helper_t * helper = NULL; 500 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 501 while (btstack_linked_list_iterator_has_next(&it)){ 502 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 503 if (item->con_handle == con_handle){ 504 helper = item; 505 break; 506 } 507 } 508 509 if (!helper) return; 510 511 // remove all connection from helper 512 btstack_linked_list_iterator_init(&it, &helper->all_connections); 513 while (btstack_linked_list_iterator_has_next(&it)){ 514 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 515 btstack_linked_list_remove(&helper->all_connections, (btstack_linked_item_t *) item); 516 free(item); 517 } 518 519 btstack_linked_list_remove(&gatt_client_helpers, (btstack_linked_item_t *) helper); 520 free(helper); 521 522 btstack_linked_list_iterator_init(&cl, &clients); 523 while (btstack_linked_list_iterator_has_next(&cl)){ 524 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 525 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 526 while (btstack_linked_list_iterator_has_next(&it)){ 527 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 528 if (item->value == con_handle){ 529 btstack_linked_list_remove(&client_state->gatt_con_handles, (btstack_linked_item_t *) item); 530 free(item); 531 } 532 } 533 } 534 } 535 #endif 536 537 static void daemon_rfcomm_close_connection(client_state_t * daemon_client){ 538 btstack_linked_list_iterator_t it; 539 btstack_linked_list_t *rfcomm_services = &daemon_client->rfcomm_services; 540 btstack_linked_list_t *rfcomm_cids = &daemon_client->rfcomm_cids; 541 542 btstack_linked_list_iterator_init(&it, rfcomm_services); 543 while (btstack_linked_list_iterator_has_next(&it)){ 544 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 545 rfcomm_unregister_service(item->value); 546 btstack_linked_list_remove(rfcomm_services, (btstack_linked_item_t *) item); 547 free(item); 548 } 549 550 btstack_linked_list_iterator_init(&it, rfcomm_cids); 551 while (btstack_linked_list_iterator_has_next(&it)){ 552 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 553 rfcomm_disconnect(item->value); 554 btstack_linked_list_remove(rfcomm_cids, (btstack_linked_item_t *) item); 555 free(item); 556 } 557 } 558 559 560 static void daemon_l2cap_close_connection(client_state_t * daemon_client){ 561 btstack_linked_list_iterator_t it; 562 btstack_linked_list_t *l2cap_psms = &daemon_client->l2cap_psms; 563 btstack_linked_list_t *l2cap_cids = &daemon_client->l2cap_cids; 564 565 btstack_linked_list_iterator_init(&it, l2cap_psms); 566 while (btstack_linked_list_iterator_has_next(&it)){ 567 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 568 l2cap_unregister_service(item->value); 569 btstack_linked_list_remove(l2cap_psms, (btstack_linked_item_t *) item); 570 free(item); 571 } 572 573 btstack_linked_list_iterator_init(&it, l2cap_cids); 574 while (btstack_linked_list_iterator_has_next(&it)){ 575 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 576 l2cap_disconnect(item->value, 0); // note: reason isn't used 577 btstack_linked_list_remove(l2cap_cids, (btstack_linked_item_t *) item); 578 free(item); 579 } 580 } 581 582 static void daemon_sdp_close_connection(client_state_t * daemon_client){ 583 btstack_linked_list_t * list = &daemon_client->sdp_record_handles; 584 btstack_linked_list_iterator_t it; 585 btstack_linked_list_iterator_init(&it, list); 586 while (btstack_linked_list_iterator_has_next(&it)){ 587 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 588 sdp_unregister_service(item->value); 589 btstack_linked_list_remove(list, (btstack_linked_item_t *) item); 590 free(item); 591 } 592 } 593 594 static connection_t * connection_for_l2cap_cid(uint16_t cid){ 595 btstack_linked_list_iterator_t cl; 596 btstack_linked_list_iterator_init(&cl, &clients); 597 while (btstack_linked_list_iterator_has_next(&cl)){ 598 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 599 btstack_linked_list_iterator_t it; 600 btstack_linked_list_iterator_init(&it, &client_state->l2cap_cids); 601 while (btstack_linked_list_iterator_has_next(&it)){ 602 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 603 if (item->value == cid){ 604 return client_state->connection; 605 } 606 } 607 } 608 return NULL; 609 } 610 611 static const uint8_t removeServiceRecordHandleAttributeIDList[] = { 0x36, 0x00, 0x05, 0x0A, 0x00, 0x01, 0xFF, 0xFF }; 612 613 // register a service record 614 // pre: AttributeIDs are in ascending order 615 // pre: ServiceRecordHandle is first attribute and is not already registered in database 616 // @returns status 617 static uint32_t daemon_sdp_create_and_register_service(uint8_t * record){ 618 619 // create new handle 620 uint32_t record_handle = sdp_create_service_record_handle(); 621 622 // calculate size of new service record: DES (2 byte len) 623 // + ServiceRecordHandle attribute (UINT16 UINT32) + size of existing attributes 624 uint16_t recordSize = 3 + (3 + 5) + de_get_data_size(record); 625 626 // alloc memory for new service record 627 uint8_t * newRecord = malloc(recordSize); 628 if (!newRecord) return 0; 629 630 // create DES for new record 631 de_create_sequence(newRecord); 632 633 // set service record handle 634 de_add_number(newRecord, DE_UINT, DE_SIZE_16, 0); 635 de_add_number(newRecord, DE_UINT, DE_SIZE_32, record_handle); 636 637 // add other attributes 638 sdp_append_attributes_in_attributeIDList(record, (uint8_t *) removeServiceRecordHandleAttributeIDList, 0, recordSize, newRecord); 639 640 uint8_t status = sdp_register_service(newRecord); 641 642 if (status) { 643 free(newRecord); 644 return 0; 645 } 646 647 return record_handle; 648 } 649 650 static connection_t * connection_for_rfcomm_cid(uint16_t cid){ 651 btstack_linked_list_iterator_t cl; 652 btstack_linked_list_iterator_init(&cl, &clients); 653 while (btstack_linked_list_iterator_has_next(&cl)){ 654 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 655 btstack_linked_list_iterator_t it; 656 btstack_linked_list_iterator_init(&it, &client_state->rfcomm_cids); 657 while (btstack_linked_list_iterator_has_next(&it)){ 658 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 659 if (item->value == cid){ 660 return client_state->connection; 661 } 662 } 663 } 664 return NULL; 665 } 666 667 #ifdef ENABLE_BLE 668 static void daemon_gatt_client_close_connection(connection_t * connection){ 669 client_state_t * client = client_for_connection(connection); 670 if (!client) return; 671 672 btstack_linked_list_iterator_t it; 673 btstack_linked_list_iterator_init(&it, &client->gatt_con_handles); 674 while (btstack_linked_list_iterator_has_next(&it)){ 675 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 676 daemon_remove_gatt_client_handle(connection, item->value); 677 } 678 } 679 #endif 680 681 static void daemon_disconnect_client(connection_t * connection){ 682 log_info("Daemon disconnect client %p\n",connection); 683 684 client_state_t * client = client_for_connection(connection); 685 if (!client) return; 686 687 daemon_sdp_close_connection(client); 688 daemon_rfcomm_close_connection(client); 689 daemon_l2cap_close_connection(client); 690 #ifdef ENABLE_BLE 691 // NOTE: experimental - disconnect all LE connections where GATT Client was used 692 // gatt_client_disconnect_connection(connection); 693 daemon_gatt_client_close_connection(connection); 694 #endif 695 696 btstack_linked_list_remove(&clients, (btstack_linked_item_t *) client); 697 free(client); 698 } 699 700 static void hci_emit_btstack_version(void){ 701 log_info("DAEMON_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 702 uint8_t event[6]; 703 event[0] = DAEMON_EVENT_VERSION; 704 event[1] = sizeof(event) - 2; 705 event[2] = BTSTACK_MAJOR; 706 event[3] = BTSTACK_MINOR; 707 little_endian_store_16(event, 4, 3257); // last SVN commit on Google Code + 1 708 socket_connection_send_packet_all(HCI_EVENT_PACKET, 0, event, sizeof(event)); 709 } 710 711 static void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 712 log_info("DAEMON_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 713 uint8_t event[3]; 714 event[0] = DAEMON_EVENT_SYSTEM_BLUETOOTH_ENABLED; 715 event[1] = sizeof(event) - 2; 716 event[2] = enabled; 717 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 718 socket_connection_send_packet_all(HCI_EVENT_PACKET, 0, event, sizeof(event)); 719 } 720 721 static void send_l2cap_connection_open_failed(connection_t * connection, bd_addr_t address, uint16_t psm, uint8_t status){ 722 // emit error - see l2cap.c:l2cap_emit_channel_opened(..) 723 uint8_t event[23]; 724 memset(event, 0, sizeof(event)); 725 event[0] = L2CAP_EVENT_CHANNEL_OPENED; 726 event[1] = sizeof(event) - 2; 727 event[2] = status; 728 reverse_bd_addr(address, &event[3]); 729 // little_endian_store_16(event, 9, channel->handle); 730 little_endian_store_16(event, 11, psm); 731 // little_endian_store_16(event, 13, channel->local_cid); 732 // little_endian_store_16(event, 15, channel->remote_cid); 733 // little_endian_store_16(event, 17, channel->local_mtu); 734 // little_endian_store_16(event, 19, channel->remote_mtu); 735 // little_endian_store_16(event, 21, channel->flush_timeout); 736 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 737 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 738 } 739 740 static void l2cap_emit_service_registered(void *connection, uint8_t status, uint16_t psm){ 741 uint8_t event[5]; 742 event[0] = DAEMON_EVENT_L2CAP_SERVICE_REGISTERED; 743 event[1] = sizeof(event) - 2; 744 event[2] = status; 745 little_endian_store_16(event, 3, psm); 746 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 747 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 748 } 749 750 static void rfcomm_emit_service_registered(void *connection, uint8_t status, uint8_t channel){ 751 uint8_t event[4]; 752 event[0] = DAEMON_EVENT_RFCOMM_SERVICE_REGISTERED; 753 event[1] = sizeof(event) - 2; 754 event[2] = status; 755 event[3] = channel; 756 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 757 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 758 } 759 760 static void send_rfcomm_create_channel_failed(void * connection, bd_addr_t addr, uint8_t server_channel, uint8_t status){ 761 // emit error - see rfcom.c:rfcomm_emit_channel_open_failed_outgoing_memory(..) 762 uint8_t event[16]; 763 memset(event, 0, sizeof(event)); 764 uint8_t pos = 0; 765 event[pos++] = RFCOMM_EVENT_CHANNEL_OPENED; 766 event[pos++] = sizeof(event) - 2; 767 event[pos++] = status; 768 reverse_bd_addr(addr, &event[pos]); pos += 6; 769 little_endian_store_16(event, pos, 0); pos += 2; 770 event[pos++] = server_channel; 771 little_endian_store_16(event, pos, 0); pos += 2; // channel ID 772 little_endian_store_16(event, pos, 0); pos += 2; // max frame size 773 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 774 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 775 } 776 777 // data: event(8), len(8), status(8), service_record_handle(32) 778 static void sdp_emit_service_registered(void *connection, uint32_t handle, uint8_t status) { 779 uint8_t event[7]; 780 event[0] = DAEMON_EVENT_SDP_SERVICE_REGISTERED; 781 event[1] = sizeof(event) - 2; 782 event[2] = status; 783 little_endian_store_32(event, 3, handle); 784 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 785 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 786 } 787 788 #ifdef ENABLE_BLE 789 790 btstack_linked_list_gatt_client_helper_t * daemon_get_gatt_client_helper(hci_con_handle_t con_handle) { 791 btstack_linked_list_iterator_t it; 792 if (!gatt_client_helpers) return NULL; 793 log_info("daemon_get_gatt_client_helper for handle 0x%02x", con_handle); 794 795 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 796 while (btstack_linked_list_iterator_has_next(&it)){ 797 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 798 if (!item ) { 799 log_info("daemon_get_gatt_client_helper gatt_client_helpers null item"); 800 break; 801 } 802 if (item->con_handle == con_handle){ 803 return item; 804 } 805 } 806 log_info("daemon_get_gatt_client_helper for handle 0x%02x is NULL.", con_handle); 807 return NULL; 808 } 809 810 static void send_gatt_query_complete(connection_t * connection, hci_con_handle_t con_handle, uint8_t status){ 811 // @format H1 812 uint8_t event[5]; 813 event[0] = GATT_EVENT_QUERY_COMPLETE; 814 event[1] = 3; 815 little_endian_store_16(event, 2, con_handle); 816 event[4] = status; 817 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 818 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 819 } 820 821 static void send_gatt_mtu_event(connection_t * connection, hci_con_handle_t con_handle, uint16_t mtu){ 822 uint8_t event[6]; 823 int pos = 0; 824 event[pos++] = GATT_EVENT_MTU; 825 event[pos++] = sizeof(event) - 2; 826 little_endian_store_16(event, pos, con_handle); 827 pos += 2; 828 little_endian_store_16(event, pos, mtu); 829 pos += 2; 830 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 831 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 832 } 833 834 btstack_linked_list_gatt_client_helper_t * daemon_setup_gatt_client_request(connection_t *connection, uint8_t *packet, int track_active_connection) { 835 hci_con_handle_t con_handle = little_endian_read_16(packet, 3); 836 log_info("daemon_setup_gatt_client_request for handle 0x%02x", con_handle); 837 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 838 if ((hci_con == NULL) || (hci_con->state != OPEN)){ 839 send_gatt_query_complete(connection, con_handle, GATT_CLIENT_NOT_CONNECTED); 840 return NULL; 841 } 842 843 btstack_linked_list_gatt_client_helper_t * helper = daemon_get_gatt_client_helper(con_handle); 844 845 if (!helper){ 846 log_info("helper does not exist"); 847 helper = calloc(sizeof(btstack_linked_list_gatt_client_helper_t), 1); 848 if (!helper) return NULL; 849 helper->con_handle = con_handle; 850 btstack_linked_list_add(&gatt_client_helpers, (btstack_linked_item_t *) helper); 851 } 852 853 if (track_active_connection && helper->active_connection){ 854 send_gatt_query_complete(connection, con_handle, GATT_CLIENT_BUSY); 855 return NULL; 856 } 857 858 daemon_add_gatt_client_handle(connection, con_handle); 859 860 if (track_active_connection){ 861 // remember connection responsible for this request 862 helper->active_connection = connection; 863 } 864 865 return helper; 866 } 867 868 // (de)serialize structs from/to HCI commands/events 869 870 void daemon_gatt_serialize_service(gatt_client_service_t * service, uint8_t * event, int offset){ 871 little_endian_store_16(event, offset, service->start_group_handle); 872 little_endian_store_16(event, offset+2, service->end_group_handle); 873 reverse_128(service->uuid128, &event[offset + 4]); 874 } 875 876 void daemon_gatt_serialize_characteristic(gatt_client_characteristic_t * characteristic, uint8_t * event, int offset){ 877 little_endian_store_16(event, offset, characteristic->start_handle); 878 little_endian_store_16(event, offset+2, characteristic->value_handle); 879 little_endian_store_16(event, offset+4, characteristic->end_handle); 880 little_endian_store_16(event, offset+6, characteristic->properties); 881 reverse_128(characteristic->uuid128, &event[offset+8]); 882 } 883 884 void daemon_gatt_serialize_characteristic_descriptor(gatt_client_characteristic_descriptor_t * characteristic_descriptor, uint8_t * event, int offset){ 885 little_endian_store_16(event, offset, characteristic_descriptor->handle); 886 reverse_128(characteristic_descriptor->uuid128, &event[offset+2]); 887 } 888 889 #endif 890 891 static int btstack_command_handler(connection_t *connection, uint8_t *packet, uint16_t size){ 892 893 bd_addr_t addr; 894 #ifdef ENABLE_BLE 895 bd_addr_type_t addr_type; 896 hci_con_handle_t handle; 897 #endif 898 uint16_t cid; 899 uint16_t psm; 900 uint16_t service_channel; 901 uint16_t mtu; 902 uint8_t reason; 903 uint8_t rfcomm_channel; 904 uint8_t rfcomm_credits; 905 uint32_t service_record_handle; 906 client_state_t *client; 907 uint8_t status; 908 uint8_t * data; 909 #if defined(HAVE_MALLOC) && defined(ENABLE_BLE) 910 uint8_t uuid128[16]; 911 gatt_client_service_t service; 912 gatt_client_characteristic_t characteristic; 913 gatt_client_characteristic_descriptor_t descriptor; 914 uint16_t data_length; 915 btstack_linked_list_gatt_client_helper_t * gatt_helper; 916 #endif 917 918 uint16_t serviceSearchPatternLen; 919 uint16_t attributeIDListLen; 920 921 // verbose log info before other info to allow for better tracking 922 hci_dump_packet( HCI_COMMAND_DATA_PACKET, 1, packet, size); 923 924 // BTstack internal commands - 16 Bit OpCode, 8 Bit ParamLen, Params... 925 switch (READ_CMD_OCF(packet)){ 926 case BTSTACK_GET_STATE: 927 log_info("BTSTACK_GET_STATE"); 928 hci_emit_state(); 929 break; 930 case BTSTACK_SET_POWER_MODE: 931 log_info("BTSTACK_SET_POWER_MODE %u", packet[3]); 932 // track client power requests 933 client = client_for_connection(connection); 934 if (!client) break; 935 client->power_mode = packet[3]; 936 // handle merged state 937 if (!clients_require_power_on()){ 938 start_power_off_timer(); 939 } else if (!power_management_sleep) { 940 stop_power_off_timer(); 941 hci_power_control(HCI_POWER_ON); 942 } 943 break; 944 case BTSTACK_GET_VERSION: 945 log_info("BTSTACK_GET_VERSION"); 946 hci_emit_btstack_version(); 947 break; 948 #ifdef HAVE_PLATFORM_IPHONE_OS 949 case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED: 950 log_info("BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED %u", packet[3]); 951 btstack_control_iphone_bt_set_enabled(packet[3]); 952 hci_emit_system_bluetooth_enabled(btstack_control_iphone_bt_enabled()); 953 break; 954 955 case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED: 956 log_info("BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED"); 957 hci_emit_system_bluetooth_enabled(btstack_control_iphone_bt_enabled()); 958 break; 959 #else 960 case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED: 961 case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED: 962 hci_emit_system_bluetooth_enabled(0); 963 break; 964 #endif 965 case BTSTACK_SET_DISCOVERABLE: 966 log_info("BTSTACK_SET_DISCOVERABLE discoverable %u)", packet[3]); 967 // track client discoverable requests 968 client = client_for_connection(connection); 969 if (!client) break; 970 client->discoverable = packet[3]; 971 // merge state 972 gap_discoverable_control(clients_require_discoverable()); 973 break; 974 case BTSTACK_SET_BLUETOOTH_ENABLED: 975 log_info("BTSTACK_SET_BLUETOOTH_ENABLED: %u\n", packet[3]); 976 if (packet[3]) { 977 // global enable 978 global_enable = 1; 979 hci_power_control(HCI_POWER_ON); 980 } else { 981 global_enable = 0; 982 clients_clear_power_request(); 983 hci_power_control(HCI_POWER_OFF); 984 } 985 break; 986 case L2CAP_CREATE_CHANNEL_MTU: 987 reverse_bd_addr(&packet[3], addr); 988 psm = little_endian_read_16(packet, 9); 989 mtu = little_endian_read_16(packet, 11); 990 status = l2cap_create_channel(NULL, addr, psm, mtu, &cid); 991 if (status){ 992 send_l2cap_connection_open_failed(connection, addr, psm, status); 993 } else { 994 daemon_add_client_l2cap_channel(connection, cid); 995 } 996 break; 997 case L2CAP_CREATE_CHANNEL: 998 reverse_bd_addr(&packet[3], addr); 999 psm = little_endian_read_16(packet, 9); 1000 mtu = 150; // until r865 1001 status = l2cap_create_channel(NULL, addr, psm, mtu, &cid); 1002 if (status){ 1003 send_l2cap_connection_open_failed(connection, addr, psm, status); 1004 } else { 1005 daemon_add_client_l2cap_channel(connection, cid); 1006 } 1007 break; 1008 case L2CAP_DISCONNECT: 1009 cid = little_endian_read_16(packet, 3); 1010 reason = packet[5]; 1011 l2cap_disconnect(cid, reason); 1012 break; 1013 case L2CAP_REGISTER_SERVICE: 1014 psm = little_endian_read_16(packet, 3); 1015 mtu = little_endian_read_16(packet, 5); 1016 status = l2cap_register_service(NULL, psm, mtu, LEVEL_0); 1017 daemon_add_client_l2cap_service(connection, little_endian_read_16(packet, 3)); 1018 l2cap_emit_service_registered(connection, status, psm); 1019 break; 1020 case L2CAP_UNREGISTER_SERVICE: 1021 psm = little_endian_read_16(packet, 3); 1022 daemon_remove_client_l2cap_service(connection, psm); 1023 l2cap_unregister_service(psm); 1024 break; 1025 case L2CAP_ACCEPT_CONNECTION: 1026 cid = little_endian_read_16(packet, 3); 1027 l2cap_accept_connection(cid); 1028 break; 1029 case L2CAP_DECLINE_CONNECTION: 1030 cid = little_endian_read_16(packet, 3); 1031 reason = packet[7]; 1032 l2cap_decline_connection(cid); 1033 break; 1034 case RFCOMM_CREATE_CHANNEL: 1035 reverse_bd_addr(&packet[3], addr); 1036 rfcomm_channel = packet[9]; 1037 status = rfcomm_create_channel(&rfcomm_packet_handler, addr, rfcomm_channel, &cid); 1038 if (status){ 1039 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status); 1040 } else { 1041 daemon_add_client_rfcomm_channel(connection, cid); 1042 } 1043 break; 1044 case RFCOMM_CREATE_CHANNEL_WITH_CREDITS: 1045 reverse_bd_addr(&packet[3], addr); 1046 rfcomm_channel = packet[9]; 1047 rfcomm_credits = packet[10]; 1048 status = rfcomm_create_channel_with_initial_credits(&rfcomm_packet_handler, addr, rfcomm_channel, rfcomm_credits, &cid ); 1049 if (status){ 1050 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status); 1051 } else { 1052 daemon_add_client_rfcomm_channel(connection, cid); 1053 } 1054 break; 1055 case RFCOMM_DISCONNECT: 1056 cid = little_endian_read_16(packet, 3); 1057 reason = packet[5]; 1058 rfcomm_disconnect(cid); 1059 break; 1060 case RFCOMM_REGISTER_SERVICE: 1061 rfcomm_channel = packet[3]; 1062 mtu = little_endian_read_16(packet, 4); 1063 status = rfcomm_register_service(&rfcomm_packet_handler, rfcomm_channel, mtu); 1064 rfcomm_emit_service_registered(connection, status, rfcomm_channel); 1065 break; 1066 case RFCOMM_REGISTER_SERVICE_WITH_CREDITS: 1067 rfcomm_channel = packet[3]; 1068 mtu = little_endian_read_16(packet, 4); 1069 rfcomm_credits = packet[6]; 1070 status = rfcomm_register_service_with_initial_credits(&rfcomm_packet_handler, rfcomm_channel, mtu, rfcomm_credits); 1071 rfcomm_emit_service_registered(connection, status, rfcomm_channel); 1072 break; 1073 case RFCOMM_UNREGISTER_SERVICE: 1074 service_channel = little_endian_read_16(packet, 3); 1075 daemon_remove_client_rfcomm_service(connection, service_channel); 1076 rfcomm_unregister_service(service_channel); 1077 break; 1078 case RFCOMM_ACCEPT_CONNECTION: 1079 cid = little_endian_read_16(packet, 3); 1080 rfcomm_accept_connection(cid); 1081 break; 1082 case RFCOMM_DECLINE_CONNECTION: 1083 cid = little_endian_read_16(packet, 3); 1084 reason = packet[7]; 1085 rfcomm_decline_connection(cid); 1086 break; 1087 case RFCOMM_GRANT_CREDITS: 1088 cid = little_endian_read_16(packet, 3); 1089 rfcomm_credits = packet[5]; 1090 rfcomm_grant_credits(cid, rfcomm_credits); 1091 break; 1092 case RFCOMM_PERSISTENT_CHANNEL: { 1093 // enforce \0 1094 packet[3+248] = 0; 1095 rfcomm_channel = rfcomm_service_db_channel_for_service((char*)&packet[3]); 1096 log_info("DAEMON_EVENT_RFCOMM_PERSISTENT_CHANNEL %u", rfcomm_channel); 1097 uint8_t event[4]; 1098 event[0] = DAEMON_EVENT_RFCOMM_PERSISTENT_CHANNEL; 1099 event[1] = sizeof(event) - 2; 1100 event[2] = 0; 1101 event[3] = rfcomm_channel; 1102 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1103 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event)); 1104 break; 1105 } 1106 case SDP_REGISTER_SERVICE_RECORD: 1107 log_info("SDP_REGISTER_SERVICE_RECORD size %u\n", size); 1108 service_record_handle = daemon_sdp_create_and_register_service(&packet[3]); 1109 if (service_record_handle){ 1110 daemon_add_client_sdp_service_record_handle(connection, service_record_handle); 1111 sdp_emit_service_registered(connection, service_record_handle, 0); 1112 } else { 1113 sdp_emit_service_registered(connection, 0, BTSTACK_MEMORY_ALLOC_FAILED); 1114 } 1115 break; 1116 case SDP_UNREGISTER_SERVICE_RECORD: 1117 service_record_handle = little_endian_read_32(packet, 3); 1118 log_info("SDP_UNREGISTER_SERVICE_RECORD handle 0x%x ", service_record_handle); 1119 data = sdp_get_record_for_handle(service_record_handle); 1120 sdp_unregister_service(service_record_handle); 1121 daemon_remove_client_sdp_service_record_handle(connection, service_record_handle); 1122 if (data){ 1123 free(data); 1124 } 1125 break; 1126 case SDP_CLIENT_QUERY_RFCOMM_SERVICES: 1127 reverse_bd_addr(&packet[3], addr); 1128 1129 serviceSearchPatternLen = de_get_len(&packet[9]); 1130 memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen); 1131 1132 sdp_client_query_connection = connection; 1133 sdp_client_query_rfcomm_channel_and_name_for_search_pattern(&handle_sdp_rfcomm_service_result, addr, serviceSearchPattern); 1134 1135 break; 1136 case SDP_CLIENT_QUERY_SERVICES: 1137 reverse_bd_addr(&packet[3], addr); 1138 sdp_client_query_connection = connection; 1139 1140 serviceSearchPatternLen = de_get_len(&packet[9]); 1141 memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen); 1142 1143 attributeIDListLen = de_get_len(&packet[9+serviceSearchPatternLen]); 1144 memcpy(attributeIDList, &packet[9+serviceSearchPatternLen], attributeIDListLen); 1145 1146 sdp_client_query(&handle_sdp_client_query_result, addr, (uint8_t*)&serviceSearchPattern[0], (uint8_t*)&attributeIDList[0]); 1147 break; 1148 #ifdef ENABLE_BLE 1149 case GAP_LE_SCAN_START: 1150 gap_start_scan(); 1151 break; 1152 case GAP_LE_SCAN_STOP: 1153 gap_stop_scan(); 1154 break; 1155 case GAP_LE_SET_SCAN_PARAMETERS: 1156 gap_set_scan_parameters(packet[3], little_endian_read_16(packet, 4), little_endian_read_16(packet, 6)); 1157 break; 1158 case GAP_LE_CONNECT: 1159 reverse_bd_addr(&packet[4], addr); 1160 addr_type = packet[3]; 1161 gap_connect(addr, addr_type); 1162 break; 1163 case GAP_LE_CONNECT_CANCEL: 1164 gap_connect_cancel(); 1165 break; 1166 case GAP_DISCONNECT: 1167 handle = little_endian_read_16(packet, 3); 1168 gap_disconnect(handle); 1169 break; 1170 #endif 1171 #if defined(HAVE_MALLOC) && defined(ENABLE_BLE) 1172 case GATT_DISCOVER_ALL_PRIMARY_SERVICES: 1173 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1174 if (!gatt_helper) break; 1175 gatt_client_discover_primary_services(&handle_gatt_client_event, gatt_helper->con_handle); 1176 break; 1177 case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID16: 1178 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1179 if (!gatt_helper) break; 1180 gatt_client_discover_primary_services_by_uuid16(&handle_gatt_client_event, gatt_helper->con_handle, little_endian_read_16(packet, 5)); 1181 break; 1182 case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID128: 1183 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1184 if (!gatt_helper) break; 1185 reverse_128(&packet[5], uuid128); 1186 gatt_client_discover_primary_services_by_uuid128(&handle_gatt_client_event, gatt_helper->con_handle, uuid128); 1187 break; 1188 case GATT_FIND_INCLUDED_SERVICES_FOR_SERVICE: 1189 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1190 if (!gatt_helper) break; 1191 gatt_client_deserialize_service(packet, 5, &service); 1192 gatt_client_find_included_services_for_service(&handle_gatt_client_event, gatt_helper->con_handle, &service); 1193 break; 1194 1195 case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE: 1196 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1197 if (!gatt_helper) break; 1198 gatt_client_deserialize_service(packet, 5, &service); 1199 gatt_client_discover_characteristics_for_service(&handle_gatt_client_event, gatt_helper->con_handle, &service); 1200 break; 1201 case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE_BY_UUID128: 1202 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1203 if (!gatt_helper) break; 1204 gatt_client_deserialize_service(packet, 5, &service); 1205 reverse_128(&packet[5 + SERVICE_LENGTH], uuid128); 1206 gatt_client_discover_characteristics_for_service_by_uuid128(&handle_gatt_client_event, gatt_helper->con_handle, &service, uuid128); 1207 break; 1208 case GATT_DISCOVER_CHARACTERISTIC_DESCRIPTORS: 1209 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1210 if (!gatt_helper) break; 1211 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1212 gatt_client_discover_characteristic_descriptors(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1213 break; 1214 1215 case GATT_READ_VALUE_OF_CHARACTERISTIC: 1216 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1217 if (!gatt_helper) break; 1218 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1219 gatt_client_read_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1220 break; 1221 case GATT_READ_LONG_VALUE_OF_CHARACTERISTIC: 1222 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1223 if (!gatt_helper) break; 1224 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1225 gatt_client_read_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1226 break; 1227 1228 case GATT_WRITE_VALUE_OF_CHARACTERISTIC_WITHOUT_RESPONSE: 1229 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 0); // note: don't track active connection 1230 if (!gatt_helper) break; 1231 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1232 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1233 data = gatt_helper->characteristic_buffer; 1234 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1235 gatt_client_write_value_of_characteristic_without_response(gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1236 break; 1237 case GATT_WRITE_VALUE_OF_CHARACTERISTIC: 1238 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1239 if (!gatt_helper) break; 1240 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1241 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1242 data = gatt_helper->characteristic_buffer; 1243 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1244 gatt_client_write_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1245 break; 1246 case GATT_WRITE_LONG_VALUE_OF_CHARACTERISTIC: 1247 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1248 if (!gatt_helper) break; 1249 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1250 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1251 data = gatt_helper->characteristic_buffer; 1252 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1253 gatt_client_write_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1254 break; 1255 case GATT_RELIABLE_WRITE_LONG_VALUE_OF_CHARACTERISTIC: 1256 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1257 if (!gatt_helper) break; 1258 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1259 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1260 data = gatt_helper->characteristic_buffer; 1261 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1262 gatt_client_write_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1263 break; 1264 case GATT_READ_CHARACTERISTIC_DESCRIPTOR: 1265 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1266 if (!gatt_helper) break; 1267 handle = little_endian_read_16(packet, 3); 1268 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1269 gatt_client_read_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor); 1270 break; 1271 case GATT_READ_LONG_CHARACTERISTIC_DESCRIPTOR: 1272 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1273 if (!gatt_helper) break; 1274 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1275 gatt_client_read_long_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor); 1276 break; 1277 1278 case GATT_WRITE_CHARACTERISTIC_DESCRIPTOR: 1279 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1280 if (!gatt_helper) break; 1281 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1282 data = gatt_helper->characteristic_buffer; 1283 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH); 1284 gatt_client_write_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor, data_length, data); 1285 break; 1286 case GATT_WRITE_LONG_CHARACTERISTIC_DESCRIPTOR: 1287 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1288 if (!gatt_helper) break; 1289 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1290 data = gatt_helper->characteristic_buffer; 1291 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH); 1292 gatt_client_write_long_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor, data_length, data); 1293 break; 1294 case GATT_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:{ 1295 uint16_t configuration = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1296 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1297 if (!gatt_helper) break; 1298 data = gatt_helper->characteristic_buffer; 1299 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1300 gatt_client_write_client_characteristic_configuration(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic, configuration); 1301 break; 1302 case GATT_GET_MTU: 1303 handle = little_endian_read_16(packet, 3); 1304 gatt_client_get_mtu(handle, &mtu); 1305 send_gatt_mtu_event(connection, handle, mtu); 1306 break; 1307 } 1308 #endif 1309 default: 1310 log_error("Error: command %u not implemented:", READ_CMD_OCF(packet)); 1311 break; 1312 } 1313 1314 return 0; 1315 } 1316 1317 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){ 1318 1319 int err = 0; 1320 client_state_t * client; 1321 1322 switch (packet_type){ 1323 case HCI_COMMAND_DATA_PACKET: 1324 if (READ_CMD_OGF(data) != OGF_BTSTACK) { 1325 // HCI Command 1326 hci_send_cmd_packet(data, length); 1327 } else { 1328 // BTstack command 1329 btstack_command_handler(connection, data, length); 1330 } 1331 break; 1332 case L2CAP_DATA_PACKET: 1333 // process l2cap packet... 1334 err = l2cap_send(channel, data, length); 1335 break; 1336 case RFCOMM_DATA_PACKET: 1337 // process l2cap packet... 1338 err = rfcomm_send(channel, data, length); 1339 break; 1340 case DAEMON_EVENT_PACKET: 1341 switch (data[0]) { 1342 case DAEMON_EVENT_CONNECTION_OPENED: 1343 log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection); 1344 1345 client = calloc(sizeof(client_state_t), 1); 1346 if (!client) break; // fail 1347 client->connection = connection; 1348 client->power_mode = HCI_POWER_OFF; 1349 client->discoverable = 0; 1350 btstack_linked_list_add(&clients, (btstack_linked_item_t *) client); 1351 break; 1352 case DAEMON_EVENT_CONNECTION_CLOSED: 1353 log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection); 1354 daemon_disconnect_client(connection); 1355 // no clients -> no HCI connections 1356 if (!clients){ 1357 hci_disconnect_all(); 1358 } 1359 1360 // update discoverable mode 1361 gap_discoverable_control(clients_require_discoverable()); 1362 // start power off, if last active client 1363 if (!clients_require_power_on()){ 1364 start_power_off_timer(); 1365 } 1366 break; 1367 default: 1368 break; 1369 } 1370 break; 1371 } 1372 if (err) { 1373 log_info("Daemon Handler: err %d\n", err); 1374 } 1375 return err; 1376 } 1377 1378 1379 static void daemon_set_logging_enabled(int enabled){ 1380 if (enabled && !loggingEnabled){ 1381 hci_dump_open(BTSTACK_LOG_FILE, BTSTACK_LOG_TYPE); 1382 } 1383 if (!enabled && loggingEnabled){ 1384 hci_dump_close(); 1385 } 1386 loggingEnabled = enabled; 1387 } 1388 1389 // local cache used to manage UI status 1390 static HCI_STATE hci_state = HCI_STATE_OFF; 1391 static int num_connections = 0; 1392 static void update_ui_status(void){ 1393 if (hci_state != HCI_STATE_WORKING) { 1394 bluetooth_status_handler(BLUETOOTH_OFF); 1395 } else { 1396 if (num_connections) { 1397 bluetooth_status_handler(BLUETOOTH_ACTIVE); 1398 } else { 1399 bluetooth_status_handler(BLUETOOTH_ON); 1400 } 1401 } 1402 } 1403 1404 #ifdef USE_SPRINGBOARD 1405 static void preferences_changed_callback(void){ 1406 int logging = platform_iphone_logging_enabled(); 1407 log_info("Logging enabled: %u\n", logging); 1408 daemon_set_logging_enabled(logging); 1409 } 1410 #endif 1411 1412 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){ 1413 1414 uint8_t update_status = 0; 1415 1416 // handle state event 1417 switch (hci_event_packet_get_type(packet)) { 1418 case BTSTACK_EVENT_STATE: 1419 hci_state = packet[2]; 1420 log_info("New state: %u\n", hci_state); 1421 update_status = 1; 1422 break; 1423 case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED: 1424 num_connections = packet[2]; 1425 log_info("New nr connections: %u\n", num_connections); 1426 update_status = 1; 1427 break; 1428 default: 1429 break; 1430 } 1431 1432 // choose full bluetooth state 1433 if (update_status) { 1434 update_ui_status(); 1435 } 1436 } 1437 1438 static void daemon_retry_parked(void){ 1439 1440 // socket_connection_retry_parked is not reentrant 1441 static int retry_mutex = 0; 1442 1443 // lock mutex 1444 if (retry_mutex) return; 1445 retry_mutex = 1; 1446 1447 // ... try sending again 1448 socket_connection_retry_parked(); 1449 1450 // unlock mutex 1451 retry_mutex = 0; 1452 } 1453 1454 #if 0 1455 1456 Minimal Code for LE Peripheral 1457 1458 enum { 1459 SET_ADVERTISEMENT_PARAMS = 1 << 0, 1460 SET_ADVERTISEMENT_DATA = 1 << 1, 1461 ENABLE_ADVERTISEMENTS = 1 << 2, 1462 }; 1463 1464 const uint8_t adv_data[] = { 1465 // Flags general discoverable 1466 0x02, 0x01, 0x02, 1467 // Name 1468 0x08, 0x09, 'B', 'T', 's', 't', 'a', 'c', 'k' 1469 }; 1470 uint8_t adv_data_len = sizeof(adv_data); 1471 static uint16_t todos = 0; 1472 1473 static void app_run(void){ 1474 1475 if (!hci_can_send_command_packet_now()) return; 1476 1477 if (todos & SET_ADVERTISEMENT_DATA){ 1478 log_info("app_run: set advertisement data\n"); 1479 todos &= ~SET_ADVERTISEMENT_DATA; 1480 hci_send_cmd(&hci_le_set_advertising_data, adv_data_len, adv_data); 1481 return; 1482 } 1483 1484 if (todos & SET_ADVERTISEMENT_PARAMS){ 1485 todos &= ~SET_ADVERTISEMENT_PARAMS; 1486 uint8_t adv_type = 0; // default 1487 bd_addr_t null_addr; 1488 memset(null_addr, 0, 6); 1489 uint16_t adv_int_min = 0x0030; 1490 uint16_t adv_int_max = 0x0030; 1491 hci_send_cmd(&hci_le_set_advertising_parameters, adv_int_min, adv_int_max, adv_type, 0, 0, &null_addr, 0x07, 0x00); 1492 return; 1493 } 1494 1495 if (todos & ENABLE_ADVERTISEMENTS){ 1496 log_info("app_run: enable advertisements\n"); 1497 todos &= ~ENABLE_ADVERTISEMENTS; 1498 hci_send_cmd(&hci_le_set_advertise_enable, 1); 1499 return; 1500 } 1501 } 1502 #endif 1503 1504 static void daemon_emit_packet(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1505 if (connection) { 1506 socket_connection_send_packet(connection, packet_type, channel, packet, size); 1507 } else { 1508 socket_connection_send_packet_all(packet_type, channel, packet, size); 1509 } 1510 } 1511 1512 static uint8_t remote_name_event[2+1+6+DEVICE_NAME_LEN+1]; // +1 for \0 in log_info 1513 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1514 uint16_t cid; 1515 int i; 1516 bd_addr_t addr; 1517 switch (packet_type) { 1518 case HCI_EVENT_PACKET: 1519 deamon_status_event_handler(packet, size); 1520 switch (hci_event_packet_get_type(packet)){ 1521 1522 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 1523 // ACL buffer freed... 1524 daemon_retry_parked(); 1525 // no need to tell clients 1526 return; 1527 1528 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 1529 if (!btstack_device_name_db) break; 1530 if (packet[2]) break; // status not ok 1531 1532 reverse_bd_addr(&packet[3], addr); 1533 // fix for invalid remote names - terminate on 0xff 1534 for (i=0; i<248;i++){ 1535 if (packet[9+i] == 0xff){ 1536 packet[9+i] = 0; 1537 break; 1538 } 1539 } 1540 packet[9+248] = 0; 1541 btstack_device_name_db->put_name(addr, (device_name_t *)&packet[9]); 1542 break; 1543 1544 case HCI_EVENT_INQUIRY_RESULT: 1545 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{ 1546 if (!btstack_device_name_db) break; 1547 1548 // first send inq result packet 1549 daemon_emit_packet(connection, packet_type, channel, packet, size); 1550 1551 // then send cached remote names 1552 int offset = 3; 1553 for (i=0; i<packet[2];i++){ 1554 reverse_bd_addr(&packet[offset], addr); 1555 if (btstack_device_name_db->get_name(addr, (device_name_t *) &remote_name_event[9])){ 1556 remote_name_event[0] = DAEMON_EVENT_REMOTE_NAME_CACHED; 1557 remote_name_event[1] = sizeof(remote_name_event) - 2 - 1; 1558 remote_name_event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 1559 reverse_bd_addr(addr, &remote_name_event[3]); 1560 1561 remote_name_event[9+248] = 0; // assert \0 for log_info 1562 log_info("DAEMON_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(addr), &remote_name_event[9]); 1563 hci_dump_packet(HCI_EVENT_PACKET, 0, remote_name_event, sizeof(remote_name_event)-1); 1564 daemon_emit_packet(connection, HCI_EVENT_PACKET, channel, remote_name_event, sizeof(remote_name_event) -1); 1565 } 1566 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2; 1567 } 1568 return; 1569 } 1570 1571 case DAEMON_EVENT_RFCOMM_CREDITS: 1572 // RFCOMM CREDITS received... 1573 daemon_retry_parked(); 1574 break; 1575 1576 case RFCOMM_EVENT_CHANNEL_OPENED: 1577 cid = little_endian_read_16(packet, 13); 1578 connection = connection_for_rfcomm_cid(cid); 1579 if (!connection) break; 1580 if (packet[2]) { 1581 daemon_remove_client_rfcomm_channel(connection, cid); 1582 } else { 1583 daemon_add_client_rfcomm_channel(connection, cid); 1584 } 1585 break; 1586 case RFCOMM_EVENT_CHANNEL_CLOSED: 1587 cid = little_endian_read_16(packet, 2); 1588 connection = connection_for_rfcomm_cid(cid); 1589 if (!connection) break; 1590 daemon_remove_client_rfcomm_channel(connection, cid); 1591 break; 1592 case DAEMON_EVENT_RFCOMM_SERVICE_REGISTERED: 1593 if (packet[2]) break; 1594 daemon_add_client_rfcomm_service(connection, packet[3]); 1595 break; 1596 case L2CAP_EVENT_CHANNEL_OPENED: 1597 cid = little_endian_read_16(packet, 13); 1598 connection = connection_for_l2cap_cid(cid); 1599 if (!connection) break; 1600 if (packet[2]) { 1601 daemon_remove_client_l2cap_channel(connection, cid); 1602 } else { 1603 daemon_add_client_l2cap_channel(connection, cid); 1604 } 1605 break; 1606 case L2CAP_EVENT_CHANNEL_CLOSED: 1607 cid = little_endian_read_16(packet, 2); 1608 connection = connection_for_l2cap_cid(cid); 1609 if (!connection) break; 1610 daemon_remove_client_l2cap_channel(connection, cid); 1611 break; 1612 #if defined(ENABLE_BLE) && defined(HAVE_MALLOC) 1613 case HCI_EVENT_DISCONNECTION_COMPLETE: 1614 log_info("daemon : ignore HCI_EVENT_DISCONNECTION_COMPLETE ingnoring."); 1615 // note: moved to gatt_client_handler because it's received here prematurely 1616 // daemon_remove_gatt_client_helper(little_endian_read_16(packet, 3)); 1617 break; 1618 #endif 1619 default: 1620 break; 1621 } 1622 break; 1623 case L2CAP_DATA_PACKET: 1624 connection = connection_for_l2cap_cid(channel); 1625 if (!connection) return; 1626 break; 1627 case RFCOMM_DATA_PACKET: 1628 connection = connection_for_l2cap_cid(channel); 1629 if (!connection) return; 1630 break; 1631 default: 1632 break; 1633 } 1634 1635 daemon_emit_packet(connection, packet_type, channel, packet, size); 1636 } 1637 1638 static void l2cap_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1639 daemon_packet_handler(NULL, packet_type, channel, packet, size); 1640 } 1641 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1642 daemon_packet_handler(NULL, packet_type, channel, packet, size); 1643 } 1644 1645 static void handle_sdp_rfcomm_service_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1646 switch (hci_event_packet_get_type(packet)){ 1647 case SDP_EVENT_QUERY_RFCOMM_SERVICE: 1648 case SDP_EVENT_QUERY_COMPLETE: 1649 // already HCI Events, just forward them 1650 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1651 socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, packet, size); 1652 break; 1653 default: 1654 break; 1655 } 1656 } 1657 1658 static void sdp_client_assert_buffer(int size){ 1659 if (size > attribute_value_buffer_size){ 1660 log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size); 1661 } 1662 } 1663 1664 // define new packet type SDP_CLIENT_PACKET 1665 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1666 int event_len; 1667 1668 switch (hci_event_packet_get_type(packet)){ 1669 case SDP_EVENT_QUERY_ATTRIBUTE_BYTE: 1670 sdp_client_assert_buffer(sdp_event_query_attribute_byte_get_attribute_length(packet)); 1671 attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet); 1672 if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)){ 1673 log_info_hexdump(attribute_value, sdp_event_query_attribute_byte_get_attribute_length(packet)); 1674 1675 int event_len = 1 + 3 * 2 + sdp_event_query_attribute_byte_get_attribute_length(packet); 1676 uint8_t event[event_len]; 1677 event[0] = SDP_EVENT_QUERY_ATTRIBUTE_VALUE; 1678 little_endian_store_16(event, 1, sdp_event_query_attribute_byte_get_record_id(packet)); 1679 little_endian_store_16(event, 3, sdp_event_query_attribute_byte_get_attribute_id(packet)); 1680 little_endian_store_16(event, 5, (uint16_t)sdp_event_query_attribute_byte_get_attribute_length(packet)); 1681 memcpy(&event[7], attribute_value, sdp_event_query_attribute_byte_get_attribute_length(packet)); 1682 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len); 1683 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len); 1684 } 1685 break; 1686 case SDP_EVENT_QUERY_COMPLETE: 1687 event_len = packet[1] + 2; 1688 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, event_len); 1689 socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, packet, event_len); 1690 break; 1691 } 1692 } 1693 1694 static void power_notification_callback(POWER_NOTIFICATION_t notification){ 1695 switch (notification) { 1696 case POWER_WILL_SLEEP: 1697 // let's sleep 1698 power_management_sleep = 1; 1699 hci_power_control(HCI_POWER_SLEEP); 1700 break; 1701 case POWER_WILL_WAKE_UP: 1702 // assume that all clients use Bluetooth -> if connection, start Bluetooth 1703 power_management_sleep = 0; 1704 if (clients_require_power_on()) { 1705 hci_power_control(HCI_POWER_ON); 1706 } 1707 break; 1708 default: 1709 break; 1710 } 1711 } 1712 1713 static void daemon_sigint_handler(int param){ 1714 1715 #ifdef HAVE_PLATFORM_IPHONE_OS 1716 // notify daemons 1717 notify_post("ch.ringwald.btstack.stopped"); 1718 #endif 1719 1720 log_info(" <= SIGINT received, shutting down..\n"); 1721 1722 hci_power_control( HCI_POWER_OFF); 1723 hci_close(); 1724 1725 log_info("Good bye, see you.\n"); 1726 1727 exit(0); 1728 } 1729 1730 // MARK: manage power off timer 1731 1732 #define USE_POWER_OFF_TIMER 1733 1734 static void stop_power_off_timer(void){ 1735 #ifdef USE_POWER_OFF_TIMER 1736 if (timeout_active) { 1737 btstack_run_loop_remove_timer(&timeout); 1738 timeout_active = 0; 1739 } 1740 #endif 1741 } 1742 1743 static void start_power_off_timer(void){ 1744 #ifdef USE_POWER_OFF_TIMER 1745 stop_power_off_timer(); 1746 btstack_run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT); 1747 btstack_run_loop_add_timer(&timeout); 1748 timeout_active = 1; 1749 #else 1750 hci_power_control(HCI_POWER_OFF); 1751 #endif 1752 } 1753 1754 // MARK: manage list of clients 1755 1756 1757 static client_state_t * client_for_connection(connection_t *connection) { 1758 btstack_linked_item_t *it; 1759 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1760 client_state_t * client_state = (client_state_t *) it; 1761 if (client_state->connection == connection) { 1762 return client_state; 1763 } 1764 } 1765 return NULL; 1766 } 1767 1768 static void clients_clear_power_request(void){ 1769 btstack_linked_item_t *it; 1770 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1771 client_state_t * client_state = (client_state_t *) it; 1772 client_state->power_mode = HCI_POWER_OFF; 1773 } 1774 } 1775 1776 static int clients_require_power_on(void){ 1777 1778 if (global_enable) return 1; 1779 1780 btstack_linked_item_t *it; 1781 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1782 client_state_t * client_state = (client_state_t *) it; 1783 if (client_state->power_mode == HCI_POWER_ON) { 1784 return 1; 1785 } 1786 } 1787 return 0; 1788 } 1789 1790 static int clients_require_discoverable(void){ 1791 btstack_linked_item_t *it; 1792 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1793 client_state_t * client_state = (client_state_t *) it; 1794 if (client_state->discoverable) { 1795 return 1; 1796 } 1797 } 1798 return 0; 1799 } 1800 1801 static void usage(const char * name) { 1802 printf("%s, BTstack background daemon\n", name); 1803 printf("usage: %s [--help] [--tcp port]\n", name); 1804 printf(" --help display this usage\n"); 1805 printf(" --tcp use TCP server on port %u\n", BTSTACK_PORT); 1806 printf("Without the --tcp option, BTstack daemon is listening on unix domain socket %s\n\n", BTSTACK_UNIX); 1807 } 1808 1809 #ifdef HAVE_PLATFORM_IPHONE_OS 1810 static void * btstack_run_loop_thread(void *context){ 1811 btstack_run_loop_execute(); 1812 return NULL; 1813 } 1814 #endif 1815 1816 #ifdef ENABLE_BLE 1817 1818 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1819 1820 // hack: handle disconnection_complete_here instead of main hci event packet handler 1821 // we receive a HCI event packet in disguise 1822 if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){ 1823 log_info("daemon hack: handle disconnection_complete in handle_gatt_client_event instead of main hci event packet handler"); 1824 hci_con_handle_t con_handle = little_endian_read_16(packet, 3); 1825 daemon_remove_gatt_client_helper(con_handle); 1826 return; 1827 } 1828 1829 // only handle GATT Events 1830 switch(hci_event_packet_get_type(packet)){ 1831 case GATT_EVENT_SERVICE_QUERY_RESULT: 1832 case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT: 1833 case GATT_EVENT_NOTIFICATION: 1834 case GATT_EVENT_INDICATION: 1835 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT: 1836 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT: 1837 case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1838 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1839 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT: 1840 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT: 1841 case GATT_EVENT_QUERY_COMPLETE: 1842 break; 1843 default: 1844 return; 1845 } 1846 1847 hci_con_handle_t con_handle = little_endian_read_16(packet, 2); 1848 btstack_linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle); 1849 if (!gatt_client_helper){ 1850 log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle); 1851 return; 1852 } 1853 1854 connection_t *connection = NULL; 1855 1856 // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections 1857 switch(hci_event_packet_get_type(packet)){ 1858 case GATT_EVENT_NOTIFICATION: 1859 case GATT_EVENT_INDICATION:{ 1860 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1861 1862 btstack_linked_item_t *it; 1863 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1864 client_state_t * client_state = (client_state_t *) it; 1865 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size); 1866 } 1867 return; 1868 } 1869 default: 1870 break; 1871 } 1872 1873 // otherwise, we have to have an active connection 1874 connection = gatt_client_helper->active_connection; 1875 uint16_t offset; 1876 uint16_t length; 1877 1878 if (!connection) return; 1879 1880 switch(hci_event_packet_get_type(packet)){ 1881 1882 case GATT_EVENT_SERVICE_QUERY_RESULT: 1883 case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT: 1884 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT: 1885 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT: 1886 case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1887 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT: 1888 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1889 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size); 1890 break; 1891 1892 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT: 1893 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1894 offset = little_endian_read_16(packet, 6); 1895 length = little_endian_read_16(packet, 8); 1896 gatt_client_helper->characteristic_buffer[0] = hci_event_packet_get_type(packet); // store type (characteristic/descriptor) 1897 gatt_client_helper->characteristic_handle = little_endian_read_16(packet, 4); // store attribute handle 1898 gatt_client_helper->characteristic_length = offset + length; // update length 1899 memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length); 1900 break; 1901 1902 case GATT_EVENT_QUERY_COMPLETE:{ 1903 gatt_client_helper->active_connection = NULL; 1904 if (gatt_client_helper->characteristic_length){ 1905 // send re-combined long characteristic value or long characteristic descriptor value 1906 uint8_t * event = gatt_client_helper->characteristic_buffer; 1907 uint16_t event_size = 10 + gatt_client_helper->characteristic_length; 1908 // event[0] == already set by previsous case 1909 event[1] = 8 + gatt_client_helper->characteristic_length; 1910 little_endian_store_16(event, 2, little_endian_read_16(packet, 2)); 1911 little_endian_store_16(event, 4, gatt_client_helper->characteristic_handle); 1912 little_endian_store_16(event, 6, 0); // offset 1913 little_endian_store_16(event, 8, gatt_client_helper->characteristic_length); 1914 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size); 1915 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size); 1916 gatt_client_helper->characteristic_length = 0; 1917 } 1918 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1919 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size); 1920 break; 1921 } 1922 default: 1923 break; 1924 } 1925 } 1926 #endif 1927 1928 static char hostname[30]; 1929 1930 int main (int argc, char * const * argv){ 1931 1932 static int tcp_flag = 0; 1933 1934 while (1) { 1935 static struct option long_options[] = { 1936 { "tcp", no_argument, &tcp_flag, 1 }, 1937 { "help", no_argument, 0, 0 }, 1938 { 0,0,0,0 } // This is a filler for -1 1939 }; 1940 1941 int c; 1942 int option_index = -1; 1943 1944 c = getopt_long(argc, argv, "h", long_options, &option_index); 1945 1946 if (c == -1) break; // no more option 1947 1948 // treat long parameter first 1949 if (option_index == -1) { 1950 switch (c) { 1951 case '?': 1952 case 'h': 1953 usage(argv[0]); 1954 return 0; 1955 break; 1956 } 1957 } else { 1958 switch (option_index) { 1959 case 1: 1960 usage(argv[0]); 1961 return 0; 1962 break; 1963 } 1964 } 1965 } 1966 1967 #ifndef HAVE_UNIX_SOCKETS 1968 // TCP is default if there are no unix sockets 1969 tcp_flag = 1; 1970 #endif 1971 1972 if (tcp_flag){ 1973 printf("BTstack Daemon started on port %u\n", BTSTACK_PORT); 1974 } else { 1975 printf("BTstack Daemon started on socket %s\n", BTSTACK_UNIX); 1976 } 1977 1978 // make stdout unbuffered 1979 setbuf(stdout, NULL); 1980 1981 // handle CTRL-c 1982 signal(SIGINT, daemon_sigint_handler); 1983 // handle SIGTERM - suggested for launchd 1984 signal(SIGTERM, daemon_sigint_handler); 1985 1986 socket_connection_init(); 1987 1988 btstack_control_t * control = NULL; 1989 void * config; 1990 const btstack_uart_block_t * uart_block_implementation = NULL; 1991 (void) uart_block_implementation; 1992 1993 #ifdef HAVE_TRANSPORT_H4 1994 hci_transport_config_uart.type = HCI_TRANSPORT_CONFIG_UART; 1995 hci_transport_config_uart.baudrate_init = UART_SPEED; 1996 hci_transport_config_uart.baudrate_main = 0; 1997 hci_transport_config_uart.flowcontrol = 1; 1998 hci_transport_config_uart.device_name = UART_DEVICE; 1999 2000 #ifndef HAVE_PLATFORM_IPHONE_OS 2001 #ifdef _WIN32 2002 uart_block_implementation = btstack_uart_block_windows_instance(); 2003 #else 2004 uart_block_implementation = btstack_uart_block_posix_instance(); 2005 #endif 2006 #endif 2007 2008 #ifdef HAVE_PLATFORM_IPHONE_OS 2009 // use default (max) UART baudrate over netgraph interface 2010 hci_transport_config_uart.baudrate_init = 0; 2011 #endif 2012 2013 config = &hci_transport_config_uart; 2014 transport = hci_transport_h4_instance(uart_block_implementation); 2015 #endif 2016 2017 #ifdef HAVE_TRANSPORT_USB 2018 transport = hci_transport_usb_instance(); 2019 #endif 2020 2021 #ifdef HAVE_PLATFORM_IPHONE_OS 2022 control = &btstack_control_iphone; 2023 if (btstack_control_iphone_power_management_supported()){ 2024 hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake"); 2025 } 2026 bluetooth_status_handler = platform_iphone_status_handler; 2027 platform_iphone_register_window_manager_restart(update_ui_status); 2028 platform_iphone_register_preferences_changed(preferences_changed_callback); 2029 #endif 2030 2031 #ifdef BTSTACK_LINK_KEY_DB_INSTANCE 2032 btstack_link_key_db = BTSTACK_LINK_KEY_DB_INSTANCE(); 2033 #endif 2034 2035 #ifdef BTSTACK_DEVICE_NAME_DB_INSTANCE 2036 btstack_device_name_db = BTSTACK_DEVICE_NAME_DB_INSTANCE(); 2037 #endif 2038 2039 #ifdef _WIN32 2040 btstack_run_loop_init(btstack_run_loop_windows_get_instance()); 2041 #else 2042 btstack_run_loop_init(btstack_run_loop_posix_get_instance()); 2043 #endif 2044 2045 // init power management notifications 2046 if (control && control->register_for_power_notifications){ 2047 control->register_for_power_notifications(power_notification_callback); 2048 } 2049 2050 // logging 2051 loggingEnabled = 0; 2052 int newLoggingEnabled = 1; 2053 #ifdef HAVE_PLATFORM_IPHONE_OS 2054 // iPhone has toggle in Preferences.app 2055 newLoggingEnabled = platform_iphone_logging_enabled(); 2056 #endif 2057 daemon_set_logging_enabled(newLoggingEnabled); 2058 2059 // dump version 2060 log_info("BTdaemon started\n"); 2061 log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE); 2062 2063 // init HCI 2064 hci_init(transport, config); 2065 if (btstack_link_key_db){ 2066 hci_set_link_key_db(btstack_link_key_db); 2067 } 2068 if (control){ 2069 hci_set_control(control); 2070 } 2071 2072 // hostname for POSIX systems 2073 gethostname(hostname, 30); 2074 hostname[29] = '\0'; 2075 gap_set_local_name(hostname); 2076 2077 #ifdef HAVE_PLATFORM_IPHONE_OS 2078 // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option 2079 gap_ssp_set_enable(0); 2080 #endif 2081 2082 // register for HCI events 2083 hci_event_callback_registration.callback = &l2cap_packet_handler; 2084 hci_add_event_handler(&hci_event_callback_registration); 2085 2086 // init L2CAP 2087 l2cap_init(); 2088 l2cap_register_packet_handler(&l2cap_packet_handler); 2089 timeout.process = daemon_no_connections_timeout; 2090 2091 #ifdef ENABLE_RFCOMM 2092 log_info("config.h: ENABLE_RFCOMM\n"); 2093 rfcomm_init(); 2094 #endif 2095 2096 #ifdef ENABLE_SDP 2097 sdp_init(); 2098 #endif 2099 2100 #ifdef ENABLE_BLE 2101 // GATT Client 2102 gatt_client_init(); 2103 2104 // sm_init(); 2105 // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY); 2106 // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION); 2107 2108 // GATT Server - empty attribute database 2109 le_device_db_init(); 2110 att_server_init(NULL, NULL, NULL); 2111 2112 #endif 2113 2114 #ifdef USE_LAUNCHD 2115 socket_connection_create_launchd(); 2116 #else 2117 // create server 2118 if (tcp_flag) { 2119 socket_connection_create_tcp(BTSTACK_PORT); 2120 } else { 2121 #ifdef HAVE_UNIX_SOCKETS 2122 socket_connection_create_unix(BTSTACK_UNIX); 2123 #endif 2124 } 2125 #endif 2126 socket_connection_register_packet_callback(&daemon_client_handler); 2127 2128 #ifdef HAVE_PLATFORM_IPHONE_OS 2129 // notify daemons 2130 notify_post("ch.ringwald.btstack.started"); 2131 2132 // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop 2133 pthread_t run_loop; 2134 pthread_create(&run_loop, NULL, &btstack_run_loop_thread, NULL); 2135 2136 // needed to receive notifications 2137 CFRunLoopRun(); 2138 #endif 2139 // go! 2140 btstack_run_loop_execute(); 2141 return 0; 2142 } 2143