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