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 81 #include "btstack_version.h" 82 #include "classic/btstack_link_key_db.h" 83 #include "classic/btstack_link_key_db_tlv.h" 84 #include "classic/rfcomm.h" 85 #include "classic/sdp_server.h" 86 #include "classic/sdp_client.h" 87 #include "classic/sdp_client_rfcomm.h" 88 #include "hci.h" 89 #include "hci_cmd.h" 90 #include "hci_dump.h" 91 #include "hci_transport.h" 92 #include "l2cap.h" 93 #include "rfcomm_service_db.h" 94 #include "socket_connection.h" 95 96 #ifdef ENABLE_BLE 97 #include "ble/gatt_client.h" 98 #include "ble/att_server.h" 99 #include "ble/att_db.h" 100 #include "ble/le_device_db.h" 101 #include "ble/le_device_db_tlv.h" 102 #include "ble/sm.h" 103 #endif 104 105 #ifdef HAVE_PLATFORM_IPHONE_OS 106 #include <CoreFoundation/CoreFoundation.h> 107 #include <notify.h> 108 #include "../port/ios/src/btstack_control_iphone.h" 109 #include "../port/ios/src/platform_iphone.h" 110 // support for "enforece wake device" in h4 - used by iOS power management 111 extern void hci_transport_h4_iphone_set_enforce_wake_device(char *path); 112 #endif 113 114 // copy of prototypes 115 const btstack_device_name_db_t * btstack_device_name_db_corefoundation_instance(void); 116 const btstack_device_name_db_t * btstack_device_name_db_fs_instance(void); 117 const btstack_link_key_db_t * btstack_link_key_db_corefoundation_instance(void); 118 const btstack_link_key_db_t * btstack_link_key_db_fs_instance(void); 119 120 #ifndef BTSTACK_LOG_FILE 121 #define BTSTACK_LOG_FILE "/tmp/hci_dump.pklg" 122 #endif 123 124 // use logger: format HCI_DUMP_PACKETLOGGER, HCI_DUMP_BLUEZ or HCI_DUMP_STDOUT 125 #ifndef BTSTACK_LOG_TYPE 126 #define BTSTACK_LOG_TYPE HCI_DUMP_PACKETLOGGER 127 #endif 128 129 #define DAEMON_NO_ACTIVE_CLIENT_TIMEOUT 10000 130 131 #define ATT_MAX_LONG_ATTRIBUTE_SIZE 512 132 133 134 #define SERVICE_LENGTH 20 135 #define CHARACTERISTIC_LENGTH 24 136 #define CHARACTERISTIC_DESCRIPTOR_LENGTH 18 137 138 // ATT_MTU - 1 139 #define ATT_MAX_ATTRIBUTE_SIZE 22 140 141 // HCI CMD OGF/OCF 142 #define READ_CMD_OGF(buffer) (buffer[1] >> 2) 143 #define READ_CMD_OCF(buffer) ((buffer[1] & 0x03) << 8 | buffer[0]) 144 145 typedef struct { 146 // linked list - assert: first field 147 btstack_linked_item_t item; 148 149 // connection 150 connection_t * connection; 151 152 btstack_linked_list_t rfcomm_cids; 153 btstack_linked_list_t rfcomm_services; 154 btstack_linked_list_t l2cap_cids; 155 btstack_linked_list_t l2cap_psms; 156 btstack_linked_list_t sdp_record_handles; 157 btstack_linked_list_t gatt_con_handles; 158 // power mode 159 HCI_POWER_MODE power_mode; 160 161 // discoverable 162 uint8_t discoverable; 163 164 } client_state_t; 165 166 typedef struct btstack_linked_list_uint32 { 167 btstack_linked_item_t item; 168 uint32_t value; 169 } btstack_linked_list_uint32_t; 170 171 typedef struct btstack_linked_list_connection { 172 btstack_linked_item_t item; 173 connection_t * connection; 174 } btstack_linked_list_connection_t; 175 176 typedef struct btstack_linked_list_gatt_client_helper{ 177 btstack_linked_item_t item; 178 hci_con_handle_t con_handle; 179 connection_t * active_connection; // the one that started the current query 180 btstack_linked_list_t all_connections; // list of all connections that ever used this helper 181 uint16_t characteristic_length; 182 uint16_t characteristic_handle; 183 uint8_t characteristic_buffer[10 + ATT_MAX_LONG_ATTRIBUTE_SIZE]; // header for sending event right away 184 uint8_t long_query_type; 185 } btstack_linked_list_gatt_client_helper_t; 186 187 // MARK: prototypes 188 static void handle_sdp_rfcomm_service_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 189 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 190 #ifdef ENABLE_BLE 191 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size); 192 #endif 193 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state); 194 static client_state_t * client_for_connection(connection_t *connection); 195 static int clients_require_power_on(void); 196 static int clients_require_discoverable(void); 197 static void clients_clear_power_request(void); 198 static void start_power_off_timer(void); 199 static void stop_power_off_timer(void); 200 static client_state_t * client_for_connection(connection_t *connection); 201 static void hci_emit_system_bluetooth_enabled(uint8_t enabled); 202 static void stack_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size); 203 204 205 // MARK: globals 206 207 #ifdef HAVE_TRANSPORT_H4 208 static hci_transport_config_uart_t hci_transport_config_uart; 209 #endif 210 211 static const hci_transport_t * transport; 212 static btstack_timer_source_t timeout; 213 static uint8_t timeout_active = 0; 214 static int power_management_sleep = 0; 215 static btstack_linked_list_t clients = NULL; // list of connected clients ` 216 #ifdef ENABLE_BLE 217 static btstack_linked_list_t gatt_client_helpers = NULL; // list of used gatt client (helpers) 218 #endif 219 220 static void (*bluetooth_status_handler)(BLUETOOTH_STATE state) = dummy_bluetooth_status_handler; 221 222 static btstack_packet_callback_registration_t hci_event_callback_registration; 223 static btstack_packet_callback_registration_t sm_event_callback_registration; 224 225 static int global_enable = 0; 226 227 static btstack_link_key_db_t const * btstack_link_key_db = NULL; 228 static btstack_device_name_db_t const * btstack_device_name_db = NULL; 229 // static int rfcomm_channel_generator = 1; 230 231 static uint8_t attribute_value[1000]; 232 static const int attribute_value_buffer_size = sizeof(attribute_value); 233 static uint8_t serviceSearchPattern[200]; 234 static uint8_t attributeIDList[50]; 235 static void * sdp_client_query_connection; 236 237 static char string_buffer[1000]; 238 239 static int loggingEnabled; 240 241 static const char * btstack_server_storage_path; 242 243 // TLV 244 static int tlv_setup_done; 245 static const btstack_tlv_t * tlv_impl; 246 static btstack_tlv_posix_t tlv_context; 247 248 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state){ 249 log_info("Bluetooth status: %u\n", state); 250 }; 251 252 static void daemon_no_connections_timeout(struct btstack_timer_source *ts){ 253 if (clients_require_power_on()) return; // false alarm :) 254 log_info("No active client connection for %u seconds -> POWER OFF\n", DAEMON_NO_ACTIVE_CLIENT_TIMEOUT/1000); 255 hci_power_control(HCI_POWER_OFF); 256 } 257 258 259 static void add_uint32_to_list(btstack_linked_list_t *list, uint32_t value){ 260 btstack_linked_list_iterator_t it; 261 btstack_linked_list_iterator_init(&it, list); 262 while (btstack_linked_list_iterator_has_next(&it)){ 263 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 264 if ( item->value == value) return; // already in list 265 } 266 267 btstack_linked_list_uint32_t * item = malloc(sizeof(btstack_linked_list_uint32_t)); 268 if (!item) return; 269 item->value = value; 270 btstack_linked_list_add(list, (btstack_linked_item_t *) item); 271 } 272 273 static void remove_and_free_uint32_from_list(btstack_linked_list_t *list, uint32_t value){ 274 btstack_linked_list_iterator_t it; 275 btstack_linked_list_iterator_init(&it, list); 276 while (btstack_linked_list_iterator_has_next(&it)){ 277 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 278 if ( item->value != value) continue; 279 btstack_linked_list_remove(list, (btstack_linked_item_t *) item); 280 free(item); 281 } 282 } 283 284 static void daemon_add_client_rfcomm_service(connection_t * connection, uint16_t service_channel){ 285 client_state_t * client_state = client_for_connection(connection); 286 if (!client_state) return; 287 add_uint32_to_list(&client_state->rfcomm_services, service_channel); 288 } 289 290 static void daemon_remove_client_rfcomm_service(connection_t * connection, uint16_t service_channel){ 291 client_state_t * client_state = client_for_connection(connection); 292 if (!client_state) return; 293 remove_and_free_uint32_from_list(&client_state->rfcomm_services, service_channel); 294 } 295 296 static void daemon_add_client_rfcomm_channel(connection_t * connection, uint16_t cid){ 297 client_state_t * client_state = client_for_connection(connection); 298 if (!client_state) return; 299 add_uint32_to_list(&client_state->rfcomm_cids, cid); 300 } 301 302 static void daemon_remove_client_rfcomm_channel(connection_t * connection, uint16_t cid){ 303 client_state_t * client_state = client_for_connection(connection); 304 if (!client_state) return; 305 remove_and_free_uint32_from_list(&client_state->rfcomm_cids, cid); 306 } 307 308 static void daemon_add_client_l2cap_service(connection_t * connection, uint16_t psm){ 309 client_state_t * client_state = client_for_connection(connection); 310 if (!client_state) return; 311 add_uint32_to_list(&client_state->l2cap_psms, psm); 312 } 313 314 static void daemon_remove_client_l2cap_service(connection_t * connection, uint16_t psm){ 315 client_state_t * client_state = client_for_connection(connection); 316 if (!client_state) return; 317 remove_and_free_uint32_from_list(&client_state->l2cap_psms, psm); 318 } 319 320 static void daemon_add_client_l2cap_channel(connection_t * connection, uint16_t cid){ 321 client_state_t * client_state = client_for_connection(connection); 322 if (!client_state) return; 323 add_uint32_to_list(&client_state->l2cap_cids, cid); 324 } 325 326 static void daemon_remove_client_l2cap_channel(connection_t * connection, uint16_t cid){ 327 client_state_t * client_state = client_for_connection(connection); 328 if (!client_state) return; 329 remove_and_free_uint32_from_list(&client_state->l2cap_cids, cid); 330 } 331 332 static void daemon_add_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){ 333 client_state_t * client_state = client_for_connection(connection); 334 if (!client_state) return; 335 add_uint32_to_list(&client_state->sdp_record_handles, handle); 336 } 337 338 static void daemon_remove_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){ 339 client_state_t * client_state = client_for_connection(connection); 340 if (!client_state) return; 341 remove_and_free_uint32_from_list(&client_state->sdp_record_handles, handle); 342 } 343 344 #ifdef ENABLE_BLE 345 static void daemon_add_gatt_client_handle(connection_t * connection, uint32_t handle){ 346 client_state_t * client_state = client_for_connection(connection); 347 if (!client_state) return; 348 349 // check if handle already exists in the gatt_con_handles list 350 btstack_linked_list_iterator_t it; 351 int handle_found = 0; 352 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 353 while (btstack_linked_list_iterator_has_next(&it)){ 354 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 355 if (item->value == handle){ 356 handle_found = 1; 357 break; 358 } 359 } 360 // if handle doesn't exist add it to gatt_con_handles 361 if (!handle_found){ 362 add_uint32_to_list(&client_state->gatt_con_handles, handle); 363 } 364 365 // check if there is a helper with given handle 366 btstack_linked_list_gatt_client_helper_t * gatt_helper = NULL; 367 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 368 while (btstack_linked_list_iterator_has_next(&it)){ 369 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 370 if (item->con_handle == handle){ 371 gatt_helper = item; 372 break; 373 } 374 } 375 376 // if gatt_helper doesn't exist, create it and add it to gatt_client_helpers list 377 if (!gatt_helper){ 378 gatt_helper = calloc(sizeof(btstack_linked_list_gatt_client_helper_t), 1); 379 if (!gatt_helper) return; 380 gatt_helper->con_handle = handle; 381 btstack_linked_list_add(&gatt_client_helpers, (btstack_linked_item_t *) gatt_helper); 382 } 383 384 // check if connection exists 385 int connection_found = 0; 386 btstack_linked_list_iterator_init(&it, &gatt_helper->all_connections); 387 while (btstack_linked_list_iterator_has_next(&it)){ 388 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 389 if (item->connection == connection){ 390 connection_found = 1; 391 break; 392 } 393 } 394 395 // if connection is not found, add it to the all_connections, and set it as active connection 396 if (!connection_found){ 397 btstack_linked_list_connection_t * con = calloc(sizeof(btstack_linked_list_connection_t), 1); 398 if (!con) return; 399 con->connection = connection; 400 btstack_linked_list_add(&gatt_helper->all_connections, (btstack_linked_item_t *)con); 401 } 402 } 403 404 405 static void daemon_remove_gatt_client_handle(connection_t * connection, uint32_t handle){ 406 // PART 1 - uses connection & handle 407 // might be extracted or vanish totally 408 client_state_t * client_state = client_for_connection(connection); 409 if (!client_state) return; 410 411 btstack_linked_list_iterator_t it; 412 // remove handle from gatt_con_handles list 413 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 414 while (btstack_linked_list_iterator_has_next(&it)){ 415 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 416 if (item->value == handle){ 417 btstack_linked_list_remove(&client_state->gatt_con_handles, (btstack_linked_item_t *) item); 418 free(item); 419 } 420 } 421 422 // PART 2 - only uses handle 423 424 // find helper with given handle 425 btstack_linked_list_gatt_client_helper_t * helper = NULL; 426 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 427 while (btstack_linked_list_iterator_has_next(&it)){ 428 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 429 if (item->con_handle == handle){ 430 helper = item; 431 break; 432 } 433 } 434 435 if (!helper) return; 436 // remove connection from helper 437 btstack_linked_list_iterator_init(&it, &helper->all_connections); 438 while (btstack_linked_list_iterator_has_next(&it)){ 439 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 440 if (item->connection == connection){ 441 btstack_linked_list_remove(&helper->all_connections, (btstack_linked_item_t *) item); 442 free(item); 443 break; 444 } 445 } 446 447 if (helper->active_connection == connection){ 448 helper->active_connection = NULL; 449 } 450 // if helper has no more connections, call disconnect 451 if (helper->all_connections == NULL){ 452 gap_disconnect((hci_con_handle_t) helper->con_handle); 453 } 454 } 455 456 457 static void daemon_remove_gatt_client_helper(uint32_t con_handle){ 458 btstack_linked_list_iterator_t it, cl; 459 // find helper with given handle 460 btstack_linked_list_gatt_client_helper_t * helper = NULL; 461 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 462 while (btstack_linked_list_iterator_has_next(&it)){ 463 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 464 if (item->con_handle == con_handle){ 465 helper = item; 466 break; 467 } 468 } 469 470 if (!helper) return; 471 472 // remove all connection from helper 473 btstack_linked_list_iterator_init(&it, &helper->all_connections); 474 while (btstack_linked_list_iterator_has_next(&it)){ 475 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 476 btstack_linked_list_remove(&helper->all_connections, (btstack_linked_item_t *) item); 477 free(item); 478 } 479 480 btstack_linked_list_remove(&gatt_client_helpers, (btstack_linked_item_t *) helper); 481 free(helper); 482 483 btstack_linked_list_iterator_init(&cl, &clients); 484 while (btstack_linked_list_iterator_has_next(&cl)){ 485 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 486 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 487 while (btstack_linked_list_iterator_has_next(&it)){ 488 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 489 if (item->value == con_handle){ 490 btstack_linked_list_remove(&client_state->gatt_con_handles, (btstack_linked_item_t *) item); 491 free(item); 492 } 493 } 494 } 495 } 496 #endif 497 498 static void daemon_rfcomm_close_connection(client_state_t * daemon_client){ 499 btstack_linked_list_iterator_t it; 500 btstack_linked_list_t *rfcomm_services = &daemon_client->rfcomm_services; 501 btstack_linked_list_t *rfcomm_cids = &daemon_client->rfcomm_cids; 502 503 btstack_linked_list_iterator_init(&it, rfcomm_services); 504 while (btstack_linked_list_iterator_has_next(&it)){ 505 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 506 rfcomm_unregister_service(item->value); 507 btstack_linked_list_remove(rfcomm_services, (btstack_linked_item_t *) item); 508 free(item); 509 } 510 511 btstack_linked_list_iterator_init(&it, rfcomm_cids); 512 while (btstack_linked_list_iterator_has_next(&it)){ 513 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 514 rfcomm_disconnect(item->value); 515 btstack_linked_list_remove(rfcomm_cids, (btstack_linked_item_t *) item); 516 free(item); 517 } 518 } 519 520 521 static void daemon_l2cap_close_connection(client_state_t * daemon_client){ 522 btstack_linked_list_iterator_t it; 523 btstack_linked_list_t *l2cap_psms = &daemon_client->l2cap_psms; 524 btstack_linked_list_t *l2cap_cids = &daemon_client->l2cap_cids; 525 526 btstack_linked_list_iterator_init(&it, l2cap_psms); 527 while (btstack_linked_list_iterator_has_next(&it)){ 528 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 529 l2cap_unregister_service(item->value); 530 btstack_linked_list_remove(l2cap_psms, (btstack_linked_item_t *) item); 531 free(item); 532 } 533 534 btstack_linked_list_iterator_init(&it, l2cap_cids); 535 while (btstack_linked_list_iterator_has_next(&it)){ 536 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 537 l2cap_disconnect(item->value, 0); // note: reason isn't used 538 btstack_linked_list_remove(l2cap_cids, (btstack_linked_item_t *) item); 539 free(item); 540 } 541 } 542 543 static void daemon_sdp_close_connection(client_state_t * daemon_client){ 544 btstack_linked_list_t * list = &daemon_client->sdp_record_handles; 545 btstack_linked_list_iterator_t it; 546 btstack_linked_list_iterator_init(&it, list); 547 while (btstack_linked_list_iterator_has_next(&it)){ 548 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 549 sdp_unregister_service(item->value); 550 btstack_linked_list_remove(list, (btstack_linked_item_t *) item); 551 free(item); 552 } 553 } 554 555 static connection_t * connection_for_l2cap_cid(uint16_t cid){ 556 btstack_linked_list_iterator_t cl; 557 btstack_linked_list_iterator_init(&cl, &clients); 558 while (btstack_linked_list_iterator_has_next(&cl)){ 559 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 560 btstack_linked_list_iterator_t it; 561 btstack_linked_list_iterator_init(&it, &client_state->l2cap_cids); 562 while (btstack_linked_list_iterator_has_next(&it)){ 563 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 564 if (item->value == cid){ 565 return client_state->connection; 566 } 567 } 568 } 569 return NULL; 570 } 571 572 static const uint8_t removeServiceRecordHandleAttributeIDList[] = { 0x36, 0x00, 0x05, 0x0A, 0x00, 0x01, 0xFF, 0xFF }; 573 574 // register a service record 575 // pre: AttributeIDs are in ascending order 576 // pre: ServiceRecordHandle is first attribute and is not already registered in database 577 // @returns status 578 static uint32_t daemon_sdp_create_and_register_service(uint8_t * record){ 579 580 // create new handle 581 uint32_t record_handle = sdp_create_service_record_handle(); 582 583 // calculate size of new service record: DES (2 byte len) 584 // + ServiceRecordHandle attribute (UINT16 UINT32) + size of existing attributes 585 uint16_t recordSize = 3 + (3 + 5) + de_get_data_size(record); 586 587 // alloc memory for new service record 588 uint8_t * newRecord = malloc(recordSize); 589 if (!newRecord) return 0; 590 591 // create DES for new record 592 de_create_sequence(newRecord); 593 594 // set service record handle 595 de_add_number(newRecord, DE_UINT, DE_SIZE_16, 0); 596 de_add_number(newRecord, DE_UINT, DE_SIZE_32, record_handle); 597 598 // add other attributes 599 sdp_append_attributes_in_attributeIDList(record, (uint8_t *) removeServiceRecordHandleAttributeIDList, 0, recordSize, newRecord); 600 601 uint8_t status = sdp_register_service(newRecord); 602 603 if (status) { 604 free(newRecord); 605 return 0; 606 } 607 608 return record_handle; 609 } 610 611 static connection_t * connection_for_rfcomm_cid(uint16_t cid){ 612 btstack_linked_list_iterator_t cl; 613 btstack_linked_list_iterator_init(&cl, &clients); 614 while (btstack_linked_list_iterator_has_next(&cl)){ 615 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 616 btstack_linked_list_iterator_t it; 617 btstack_linked_list_iterator_init(&it, &client_state->rfcomm_cids); 618 while (btstack_linked_list_iterator_has_next(&it)){ 619 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 620 if (item->value == cid){ 621 return client_state->connection; 622 } 623 } 624 } 625 return NULL; 626 } 627 628 #ifdef ENABLE_BLE 629 static void daemon_gatt_client_close_connection(connection_t * connection){ 630 client_state_t * client = client_for_connection(connection); 631 if (!client) return; 632 633 btstack_linked_list_iterator_t it; 634 btstack_linked_list_iterator_init(&it, &client->gatt_con_handles); 635 while (btstack_linked_list_iterator_has_next(&it)){ 636 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 637 daemon_remove_gatt_client_handle(connection, item->value); 638 } 639 } 640 #endif 641 642 static void daemon_disconnect_client(connection_t * connection){ 643 log_info("Daemon disconnect client %p\n",connection); 644 645 client_state_t * client = client_for_connection(connection); 646 if (!client) return; 647 648 daemon_sdp_close_connection(client); 649 daemon_rfcomm_close_connection(client); 650 daemon_l2cap_close_connection(client); 651 #ifdef ENABLE_BLE 652 // NOTE: experimental - disconnect all LE connections where GATT Client was used 653 // gatt_client_disconnect_connection(connection); 654 daemon_gatt_client_close_connection(connection); 655 #endif 656 657 btstack_linked_list_remove(&clients, (btstack_linked_item_t *) client); 658 free(client); 659 } 660 661 static void hci_emit_btstack_version(void){ 662 log_info("DAEMON_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 663 uint8_t event[6]; 664 event[0] = DAEMON_EVENT_VERSION; 665 event[1] = sizeof(event) - 2; 666 event[2] = BTSTACK_MAJOR; 667 event[3] = BTSTACK_MINOR; 668 little_endian_store_16(event, 4, 3257); // last SVN commit on Google Code + 1 669 socket_connection_send_packet_all(HCI_EVENT_PACKET, 0, event, sizeof(event)); 670 } 671 672 static void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 673 log_info("DAEMON_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 674 uint8_t event[3]; 675 event[0] = DAEMON_EVENT_SYSTEM_BLUETOOTH_ENABLED; 676 event[1] = sizeof(event) - 2; 677 event[2] = enabled; 678 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 679 socket_connection_send_packet_all(HCI_EVENT_PACKET, 0, event, sizeof(event)); 680 } 681 682 static void send_l2cap_connection_open_failed(connection_t * connection, bd_addr_t address, uint16_t psm, uint8_t status){ 683 // emit error - see l2cap.c:l2cap_emit_channel_opened(..) 684 uint8_t event[23]; 685 memset(event, 0, sizeof(event)); 686 event[0] = L2CAP_EVENT_CHANNEL_OPENED; 687 event[1] = sizeof(event) - 2; 688 event[2] = status; 689 reverse_bd_addr(address, &event[3]); 690 // little_endian_store_16(event, 9, channel->handle); 691 little_endian_store_16(event, 11, psm); 692 // little_endian_store_16(event, 13, channel->local_cid); 693 // little_endian_store_16(event, 15, channel->remote_cid); 694 // little_endian_store_16(event, 17, channel->local_mtu); 695 // little_endian_store_16(event, 19, channel->remote_mtu); 696 // little_endian_store_16(event, 21, channel->flush_timeout); 697 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 698 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 699 } 700 701 static void l2cap_emit_service_registered(void *connection, uint8_t status, uint16_t psm){ 702 uint8_t event[5]; 703 event[0] = DAEMON_EVENT_L2CAP_SERVICE_REGISTERED; 704 event[1] = sizeof(event) - 2; 705 event[2] = status; 706 little_endian_store_16(event, 3, psm); 707 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 708 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 709 } 710 711 static void rfcomm_emit_service_registered(void *connection, uint8_t status, uint8_t channel){ 712 uint8_t event[4]; 713 event[0] = DAEMON_EVENT_RFCOMM_SERVICE_REGISTERED; 714 event[1] = sizeof(event) - 2; 715 event[2] = status; 716 event[3] = channel; 717 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 718 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 719 } 720 721 static void send_rfcomm_create_channel_failed(void * connection, bd_addr_t addr, uint8_t server_channel, uint8_t status){ 722 // emit error - see rfcom.c:rfcomm_emit_channel_open_failed_outgoing_memory(..) 723 uint8_t event[16]; 724 memset(event, 0, sizeof(event)); 725 uint8_t pos = 0; 726 event[pos++] = RFCOMM_EVENT_CHANNEL_OPENED; 727 event[pos++] = sizeof(event) - 2; 728 event[pos++] = status; 729 reverse_bd_addr(addr, &event[pos]); pos += 6; 730 little_endian_store_16(event, pos, 0); pos += 2; 731 event[pos++] = server_channel; 732 little_endian_store_16(event, pos, 0); pos += 2; // channel ID 733 little_endian_store_16(event, pos, 0); pos += 2; // max frame size 734 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 735 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 736 } 737 738 // data: event(8), len(8), status(8), service_record_handle(32) 739 static void sdp_emit_service_registered(void *connection, uint32_t handle, uint8_t status) { 740 uint8_t event[7]; 741 event[0] = DAEMON_EVENT_SDP_SERVICE_REGISTERED; 742 event[1] = sizeof(event) - 2; 743 event[2] = status; 744 little_endian_store_32(event, 3, handle); 745 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 746 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 747 } 748 749 #ifdef ENABLE_BLE 750 751 btstack_linked_list_gatt_client_helper_t * daemon_get_gatt_client_helper(hci_con_handle_t con_handle) { 752 btstack_linked_list_iterator_t it; 753 if (!gatt_client_helpers) return NULL; 754 log_info("daemon_get_gatt_client_helper for handle 0x%02x", con_handle); 755 756 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 757 while (btstack_linked_list_iterator_has_next(&it)){ 758 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 759 if (!item ) { 760 log_info("daemon_get_gatt_client_helper gatt_client_helpers null item"); 761 break; 762 } 763 if (item->con_handle == con_handle){ 764 return item; 765 } 766 } 767 log_info("daemon_get_gatt_client_helper for handle 0x%02x is NULL.", con_handle); 768 return NULL; 769 } 770 771 static void send_gatt_query_complete(connection_t * connection, hci_con_handle_t con_handle, uint8_t status){ 772 // @format H1 773 uint8_t event[5]; 774 event[0] = GATT_EVENT_QUERY_COMPLETE; 775 event[1] = 3; 776 little_endian_store_16(event, 2, con_handle); 777 event[4] = status; 778 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 779 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 780 } 781 782 static void send_gatt_mtu_event(connection_t * connection, hci_con_handle_t con_handle, uint16_t mtu){ 783 uint8_t event[6]; 784 int pos = 0; 785 event[pos++] = GATT_EVENT_MTU; 786 event[pos++] = sizeof(event) - 2; 787 little_endian_store_16(event, pos, con_handle); 788 pos += 2; 789 little_endian_store_16(event, pos, mtu); 790 pos += 2; 791 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 792 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 793 } 794 795 btstack_linked_list_gatt_client_helper_t * daemon_setup_gatt_client_request(connection_t *connection, uint8_t *packet, int track_active_connection) { 796 hci_con_handle_t con_handle = little_endian_read_16(packet, 3); 797 log_info("daemon_setup_gatt_client_request for handle 0x%02x", con_handle); 798 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 799 if ((hci_con == NULL) || (hci_con->state != OPEN)){ 800 send_gatt_query_complete(connection, con_handle, GATT_CLIENT_NOT_CONNECTED); 801 return NULL; 802 } 803 804 btstack_linked_list_gatt_client_helper_t * helper = daemon_get_gatt_client_helper(con_handle); 805 806 if (!helper){ 807 log_info("helper does not exist"); 808 helper = calloc(sizeof(btstack_linked_list_gatt_client_helper_t), 1); 809 if (!helper) return NULL; 810 helper->con_handle = con_handle; 811 btstack_linked_list_add(&gatt_client_helpers, (btstack_linked_item_t *) helper); 812 } 813 814 if (track_active_connection && helper->active_connection){ 815 send_gatt_query_complete(connection, con_handle, GATT_CLIENT_BUSY); 816 return NULL; 817 } 818 819 daemon_add_gatt_client_handle(connection, con_handle); 820 821 if (track_active_connection){ 822 // remember connection responsible for this request 823 helper->active_connection = connection; 824 } 825 826 return helper; 827 } 828 829 // (de)serialize structs from/to HCI commands/events 830 831 void daemon_gatt_serialize_service(gatt_client_service_t * service, uint8_t * event, int offset){ 832 little_endian_store_16(event, offset, service->start_group_handle); 833 little_endian_store_16(event, offset+2, service->end_group_handle); 834 reverse_128(service->uuid128, &event[offset + 4]); 835 } 836 837 void daemon_gatt_serialize_characteristic(gatt_client_characteristic_t * characteristic, uint8_t * event, int offset){ 838 little_endian_store_16(event, offset, characteristic->start_handle); 839 little_endian_store_16(event, offset+2, characteristic->value_handle); 840 little_endian_store_16(event, offset+4, characteristic->end_handle); 841 little_endian_store_16(event, offset+6, characteristic->properties); 842 reverse_128(characteristic->uuid128, &event[offset+8]); 843 } 844 845 void daemon_gatt_serialize_characteristic_descriptor(gatt_client_characteristic_descriptor_t * characteristic_descriptor, uint8_t * event, int offset){ 846 little_endian_store_16(event, offset, characteristic_descriptor->handle); 847 reverse_128(characteristic_descriptor->uuid128, &event[offset+2]); 848 } 849 850 #endif 851 852 static int btstack_command_handler(connection_t *connection, uint8_t *packet, uint16_t size){ 853 854 bd_addr_t addr; 855 #ifdef ENABLE_BLE 856 bd_addr_type_t addr_type; 857 hci_con_handle_t handle; 858 #endif 859 uint16_t cid; 860 uint16_t psm; 861 uint16_t service_channel; 862 uint16_t mtu; 863 uint8_t reason; 864 uint8_t rfcomm_channel; 865 uint8_t rfcomm_credits; 866 uint32_t service_record_handle; 867 client_state_t *client; 868 uint8_t status; 869 uint8_t * data; 870 #if defined(HAVE_MALLOC) && defined(ENABLE_BLE) 871 uint8_t uuid128[16]; 872 gatt_client_service_t service; 873 gatt_client_characteristic_t characteristic; 874 gatt_client_characteristic_descriptor_t descriptor; 875 uint16_t data_length; 876 btstack_linked_list_gatt_client_helper_t * gatt_helper; 877 #endif 878 879 uint16_t serviceSearchPatternLen; 880 uint16_t attributeIDListLen; 881 882 // verbose log info before other info to allow for better tracking 883 hci_dump_packet( HCI_COMMAND_DATA_PACKET, 1, packet, size); 884 885 // BTstack internal commands - 16 Bit OpCode, 8 Bit ParamLen, Params... 886 switch (READ_CMD_OCF(packet)){ 887 case BTSTACK_GET_STATE: 888 log_info("BTSTACK_GET_STATE"); 889 hci_emit_state(); 890 break; 891 case BTSTACK_SET_POWER_MODE: 892 log_info("BTSTACK_SET_POWER_MODE %u", packet[3]); 893 // track client power requests 894 client = client_for_connection(connection); 895 if (!client) break; 896 client->power_mode = packet[3]; 897 // handle merged state 898 if (!clients_require_power_on()){ 899 start_power_off_timer(); 900 } else if (!power_management_sleep) { 901 stop_power_off_timer(); 902 hci_power_control(HCI_POWER_ON); 903 } 904 break; 905 case BTSTACK_GET_VERSION: 906 log_info("BTSTACK_GET_VERSION"); 907 hci_emit_btstack_version(); 908 break; 909 #ifdef HAVE_PLATFORM_IPHONE_OS 910 case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED: 911 log_info("BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED %u", packet[3]); 912 btstack_control_iphone_bt_set_enabled(packet[3]); 913 hci_emit_system_bluetooth_enabled(btstack_control_iphone_bt_enabled()); 914 break; 915 916 case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED: 917 log_info("BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED"); 918 hci_emit_system_bluetooth_enabled(btstack_control_iphone_bt_enabled()); 919 break; 920 #else 921 case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED: 922 case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED: 923 hci_emit_system_bluetooth_enabled(0); 924 break; 925 #endif 926 case BTSTACK_SET_DISCOVERABLE: 927 log_info("BTSTACK_SET_DISCOVERABLE discoverable %u)", packet[3]); 928 // track client discoverable requests 929 client = client_for_connection(connection); 930 if (!client) break; 931 client->discoverable = packet[3]; 932 // merge state 933 gap_discoverable_control(clients_require_discoverable()); 934 break; 935 case BTSTACK_SET_BLUETOOTH_ENABLED: 936 log_info("BTSTACK_SET_BLUETOOTH_ENABLED: %u\n", packet[3]); 937 if (packet[3]) { 938 // global enable 939 global_enable = 1; 940 hci_power_control(HCI_POWER_ON); 941 } else { 942 global_enable = 0; 943 clients_clear_power_request(); 944 hci_power_control(HCI_POWER_OFF); 945 } 946 break; 947 case L2CAP_CREATE_CHANNEL_MTU: 948 reverse_bd_addr(&packet[3], addr); 949 psm = little_endian_read_16(packet, 9); 950 mtu = little_endian_read_16(packet, 11); 951 status = l2cap_create_channel(NULL, addr, psm, mtu, &cid); 952 if (status){ 953 send_l2cap_connection_open_failed(connection, addr, psm, status); 954 } else { 955 daemon_add_client_l2cap_channel(connection, cid); 956 } 957 break; 958 case L2CAP_CREATE_CHANNEL: 959 reverse_bd_addr(&packet[3], addr); 960 psm = little_endian_read_16(packet, 9); 961 mtu = 150; // until r865 962 status = l2cap_create_channel(NULL, addr, psm, mtu, &cid); 963 if (status){ 964 send_l2cap_connection_open_failed(connection, addr, psm, status); 965 } else { 966 daemon_add_client_l2cap_channel(connection, cid); 967 } 968 break; 969 case L2CAP_DISCONNECT: 970 cid = little_endian_read_16(packet, 3); 971 reason = packet[5]; 972 l2cap_disconnect(cid, reason); 973 break; 974 case L2CAP_REGISTER_SERVICE: 975 psm = little_endian_read_16(packet, 3); 976 mtu = little_endian_read_16(packet, 5); 977 status = l2cap_register_service(NULL, psm, mtu, LEVEL_0); 978 daemon_add_client_l2cap_service(connection, little_endian_read_16(packet, 3)); 979 l2cap_emit_service_registered(connection, status, psm); 980 break; 981 case L2CAP_UNREGISTER_SERVICE: 982 psm = little_endian_read_16(packet, 3); 983 daemon_remove_client_l2cap_service(connection, psm); 984 l2cap_unregister_service(psm); 985 break; 986 case L2CAP_ACCEPT_CONNECTION: 987 cid = little_endian_read_16(packet, 3); 988 l2cap_accept_connection(cid); 989 break; 990 case L2CAP_DECLINE_CONNECTION: 991 cid = little_endian_read_16(packet, 3); 992 reason = packet[7]; 993 l2cap_decline_connection(cid); 994 break; 995 case RFCOMM_CREATE_CHANNEL: 996 reverse_bd_addr(&packet[3], addr); 997 rfcomm_channel = packet[9]; 998 status = rfcomm_create_channel(&stack_packet_handler, addr, rfcomm_channel, &cid); 999 if (status){ 1000 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status); 1001 } else { 1002 daemon_add_client_rfcomm_channel(connection, cid); 1003 } 1004 break; 1005 case RFCOMM_CREATE_CHANNEL_WITH_CREDITS: 1006 reverse_bd_addr(&packet[3], addr); 1007 rfcomm_channel = packet[9]; 1008 rfcomm_credits = packet[10]; 1009 status = rfcomm_create_channel_with_initial_credits(&stack_packet_handler, addr, rfcomm_channel, rfcomm_credits, &cid ); 1010 if (status){ 1011 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status); 1012 } else { 1013 daemon_add_client_rfcomm_channel(connection, cid); 1014 } 1015 break; 1016 case RFCOMM_DISCONNECT: 1017 cid = little_endian_read_16(packet, 3); 1018 reason = packet[5]; 1019 rfcomm_disconnect(cid); 1020 break; 1021 case RFCOMM_REGISTER_SERVICE: 1022 rfcomm_channel = packet[3]; 1023 mtu = little_endian_read_16(packet, 4); 1024 status = rfcomm_register_service(&stack_packet_handler, rfcomm_channel, mtu); 1025 rfcomm_emit_service_registered(connection, status, rfcomm_channel); 1026 break; 1027 case RFCOMM_REGISTER_SERVICE_WITH_CREDITS: 1028 rfcomm_channel = packet[3]; 1029 mtu = little_endian_read_16(packet, 4); 1030 rfcomm_credits = packet[6]; 1031 status = rfcomm_register_service_with_initial_credits(&stack_packet_handler, rfcomm_channel, mtu, rfcomm_credits); 1032 rfcomm_emit_service_registered(connection, status, rfcomm_channel); 1033 break; 1034 case RFCOMM_UNREGISTER_SERVICE: 1035 service_channel = little_endian_read_16(packet, 3); 1036 daemon_remove_client_rfcomm_service(connection, service_channel); 1037 rfcomm_unregister_service(service_channel); 1038 break; 1039 case RFCOMM_ACCEPT_CONNECTION: 1040 cid = little_endian_read_16(packet, 3); 1041 rfcomm_accept_connection(cid); 1042 break; 1043 case RFCOMM_DECLINE_CONNECTION: 1044 cid = little_endian_read_16(packet, 3); 1045 reason = packet[7]; 1046 rfcomm_decline_connection(cid); 1047 break; 1048 case RFCOMM_GRANT_CREDITS: 1049 cid = little_endian_read_16(packet, 3); 1050 rfcomm_credits = packet[5]; 1051 rfcomm_grant_credits(cid, rfcomm_credits); 1052 break; 1053 case RFCOMM_PERSISTENT_CHANNEL: { 1054 // enforce \0 1055 packet[3+248] = 0; 1056 rfcomm_channel = rfcomm_service_db_channel_for_service((char*)&packet[3]); 1057 log_info("DAEMON_EVENT_RFCOMM_PERSISTENT_CHANNEL %u", rfcomm_channel); 1058 uint8_t event[4]; 1059 event[0] = DAEMON_EVENT_RFCOMM_PERSISTENT_CHANNEL; 1060 event[1] = sizeof(event) - 2; 1061 event[2] = 0; 1062 event[3] = rfcomm_channel; 1063 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1064 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event)); 1065 break; 1066 } 1067 case SDP_REGISTER_SERVICE_RECORD: 1068 log_info("SDP_REGISTER_SERVICE_RECORD size %u\n", size); 1069 service_record_handle = daemon_sdp_create_and_register_service(&packet[3]); 1070 if (service_record_handle){ 1071 daemon_add_client_sdp_service_record_handle(connection, service_record_handle); 1072 sdp_emit_service_registered(connection, service_record_handle, 0); 1073 } else { 1074 sdp_emit_service_registered(connection, 0, BTSTACK_MEMORY_ALLOC_FAILED); 1075 } 1076 break; 1077 case SDP_UNREGISTER_SERVICE_RECORD: 1078 service_record_handle = little_endian_read_32(packet, 3); 1079 log_info("SDP_UNREGISTER_SERVICE_RECORD handle 0x%x ", service_record_handle); 1080 data = sdp_get_record_for_handle(service_record_handle); 1081 sdp_unregister_service(service_record_handle); 1082 daemon_remove_client_sdp_service_record_handle(connection, service_record_handle); 1083 if (data){ 1084 free(data); 1085 } 1086 break; 1087 case SDP_CLIENT_QUERY_RFCOMM_SERVICES: 1088 reverse_bd_addr(&packet[3], addr); 1089 1090 serviceSearchPatternLen = de_get_len(&packet[9]); 1091 memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen); 1092 1093 sdp_client_query_connection = connection; 1094 sdp_client_query_rfcomm_channel_and_name_for_search_pattern(&handle_sdp_rfcomm_service_result, addr, serviceSearchPattern); 1095 1096 break; 1097 case SDP_CLIENT_QUERY_SERVICES: 1098 reverse_bd_addr(&packet[3], addr); 1099 sdp_client_query_connection = connection; 1100 1101 serviceSearchPatternLen = de_get_len(&packet[9]); 1102 memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen); 1103 1104 attributeIDListLen = de_get_len(&packet[9+serviceSearchPatternLen]); 1105 memcpy(attributeIDList, &packet[9+serviceSearchPatternLen], attributeIDListLen); 1106 1107 sdp_client_query(&handle_sdp_client_query_result, addr, (uint8_t*)&serviceSearchPattern[0], (uint8_t*)&attributeIDList[0]); 1108 break; 1109 #ifdef ENABLE_BLE 1110 case GAP_LE_SCAN_START: 1111 gap_start_scan(); 1112 break; 1113 case GAP_LE_SCAN_STOP: 1114 gap_stop_scan(); 1115 break; 1116 case GAP_LE_SET_SCAN_PARAMETERS: 1117 gap_set_scan_parameters(packet[3], little_endian_read_16(packet, 4), little_endian_read_16(packet, 6)); 1118 break; 1119 case GAP_LE_CONNECT: 1120 reverse_bd_addr(&packet[4], addr); 1121 addr_type = packet[3]; 1122 gap_connect(addr, addr_type); 1123 break; 1124 case GAP_LE_CONNECT_CANCEL: 1125 gap_connect_cancel(); 1126 break; 1127 case GAP_DISCONNECT: 1128 handle = little_endian_read_16(packet, 3); 1129 gap_disconnect(handle); 1130 break; 1131 #endif 1132 #if defined(HAVE_MALLOC) && defined(ENABLE_BLE) 1133 case GATT_DISCOVER_ALL_PRIMARY_SERVICES: 1134 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1135 if (!gatt_helper) break; 1136 gatt_client_discover_primary_services(&handle_gatt_client_event, gatt_helper->con_handle); 1137 break; 1138 case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID16: 1139 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1140 if (!gatt_helper) break; 1141 gatt_client_discover_primary_services_by_uuid16(&handle_gatt_client_event, gatt_helper->con_handle, little_endian_read_16(packet, 5)); 1142 break; 1143 case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID128: 1144 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1145 if (!gatt_helper) break; 1146 reverse_128(&packet[5], uuid128); 1147 gatt_client_discover_primary_services_by_uuid128(&handle_gatt_client_event, gatt_helper->con_handle, uuid128); 1148 break; 1149 case GATT_FIND_INCLUDED_SERVICES_FOR_SERVICE: 1150 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1151 if (!gatt_helper) break; 1152 gatt_client_deserialize_service(packet, 5, &service); 1153 gatt_client_find_included_services_for_service(&handle_gatt_client_event, gatt_helper->con_handle, &service); 1154 break; 1155 1156 case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE: 1157 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1158 if (!gatt_helper) break; 1159 gatt_client_deserialize_service(packet, 5, &service); 1160 gatt_client_discover_characteristics_for_service(&handle_gatt_client_event, gatt_helper->con_handle, &service); 1161 break; 1162 case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE_BY_UUID128: 1163 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1164 if (!gatt_helper) break; 1165 gatt_client_deserialize_service(packet, 5, &service); 1166 reverse_128(&packet[5 + SERVICE_LENGTH], uuid128); 1167 gatt_client_discover_characteristics_for_service_by_uuid128(&handle_gatt_client_event, gatt_helper->con_handle, &service, uuid128); 1168 break; 1169 case GATT_DISCOVER_CHARACTERISTIC_DESCRIPTORS: 1170 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1171 if (!gatt_helper) break; 1172 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1173 gatt_client_discover_characteristic_descriptors(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1174 break; 1175 1176 case GATT_READ_VALUE_OF_CHARACTERISTIC: 1177 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1178 if (!gatt_helper) break; 1179 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1180 gatt_client_read_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1181 break; 1182 case GATT_READ_LONG_VALUE_OF_CHARACTERISTIC: 1183 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1184 if (!gatt_helper) break; 1185 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1186 gatt_client_read_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1187 break; 1188 1189 case GATT_WRITE_VALUE_OF_CHARACTERISTIC_WITHOUT_RESPONSE: 1190 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 0); // note: don't track active connection 1191 if (!gatt_helper) break; 1192 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1193 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1194 data = gatt_helper->characteristic_buffer; 1195 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1196 gatt_client_write_value_of_characteristic_without_response(gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1197 break; 1198 case GATT_WRITE_VALUE_OF_CHARACTERISTIC: 1199 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1200 if (!gatt_helper) break; 1201 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1202 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1203 data = gatt_helper->characteristic_buffer; 1204 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1205 gatt_client_write_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1206 break; 1207 case GATT_WRITE_LONG_VALUE_OF_CHARACTERISTIC: 1208 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1209 if (!gatt_helper) break; 1210 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1211 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1212 data = gatt_helper->characteristic_buffer; 1213 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1214 gatt_client_write_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1215 break; 1216 case GATT_RELIABLE_WRITE_LONG_VALUE_OF_CHARACTERISTIC: 1217 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1218 if (!gatt_helper) break; 1219 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1220 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1221 data = gatt_helper->characteristic_buffer; 1222 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1223 gatt_client_write_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1224 break; 1225 case GATT_READ_CHARACTERISTIC_DESCRIPTOR: 1226 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1227 if (!gatt_helper) break; 1228 handle = little_endian_read_16(packet, 3); 1229 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1230 gatt_client_read_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor); 1231 break; 1232 case GATT_READ_LONG_CHARACTERISTIC_DESCRIPTOR: 1233 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1234 if (!gatt_helper) break; 1235 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1236 gatt_client_read_long_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor); 1237 break; 1238 1239 case GATT_WRITE_CHARACTERISTIC_DESCRIPTOR: 1240 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1241 if (!gatt_helper) break; 1242 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1243 data = gatt_helper->characteristic_buffer; 1244 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH); 1245 gatt_client_write_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor, data_length, data); 1246 break; 1247 case GATT_WRITE_LONG_CHARACTERISTIC_DESCRIPTOR: 1248 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1249 if (!gatt_helper) break; 1250 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1251 data = gatt_helper->characteristic_buffer; 1252 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH); 1253 gatt_client_write_long_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor, data_length, data); 1254 break; 1255 case GATT_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:{ 1256 uint16_t configuration = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1257 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1258 if (!gatt_helper) break; 1259 data = gatt_helper->characteristic_buffer; 1260 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1261 gatt_client_write_client_characteristic_configuration(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic, configuration); 1262 break; 1263 case GATT_GET_MTU: 1264 handle = little_endian_read_16(packet, 3); 1265 gatt_client_get_mtu(handle, &mtu); 1266 send_gatt_mtu_event(connection, handle, mtu); 1267 break; 1268 } 1269 #endif 1270 #ifdef ENABLE_BLE 1271 case SM_SET_AUTHENTICATION_REQUIREMENTS: 1272 sm_set_authentication_requirements(packet[3]); 1273 break; 1274 case SM_SET_IO_CAPABILITIES: 1275 sm_set_io_capabilities(packet[3]); 1276 break; 1277 case SM_BONDING_DECLINE: 1278 sm_bonding_decline(little_endian_read_16(packet, 3)); 1279 break; 1280 case SM_JUST_WORKS_CONFIRM: 1281 sm_just_works_confirm(little_endian_read_16(packet, 3)); 1282 break; 1283 case SM_NUMERIC_COMPARISON_CONFIRM: 1284 sm_numeric_comparison_confirm(little_endian_read_16(packet, 3)); 1285 break; 1286 case SM_PASSKEY_INPUT: 1287 sm_passkey_input(little_endian_read_16(packet, 3), little_endian_read_32(packet, 5)); 1288 break; 1289 #endif 1290 default: 1291 log_error("Error: command %u not implemented:", READ_CMD_OCF(packet)); 1292 break; 1293 } 1294 1295 return 0; 1296 } 1297 1298 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){ 1299 1300 int err = 0; 1301 client_state_t * client; 1302 1303 switch (packet_type){ 1304 case HCI_COMMAND_DATA_PACKET: 1305 if (READ_CMD_OGF(data) != OGF_BTSTACK) { 1306 // HCI Command 1307 hci_send_cmd_packet(data, length); 1308 } else { 1309 // BTstack command 1310 btstack_command_handler(connection, data, length); 1311 } 1312 break; 1313 case L2CAP_DATA_PACKET: 1314 // process l2cap packet... 1315 err = l2cap_send(channel, data, length); 1316 break; 1317 case RFCOMM_DATA_PACKET: 1318 // process l2cap packet... 1319 err = rfcomm_send(channel, data, length); 1320 break; 1321 case DAEMON_EVENT_PACKET: 1322 switch (data[0]) { 1323 case DAEMON_EVENT_CONNECTION_OPENED: 1324 log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection); 1325 1326 client = calloc(sizeof(client_state_t), 1); 1327 if (!client) break; // fail 1328 client->connection = connection; 1329 client->power_mode = HCI_POWER_OFF; 1330 client->discoverable = 0; 1331 btstack_linked_list_add(&clients, (btstack_linked_item_t *) client); 1332 break; 1333 case DAEMON_EVENT_CONNECTION_CLOSED: 1334 log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection); 1335 daemon_disconnect_client(connection); 1336 // no clients -> no HCI connections 1337 if (!clients){ 1338 hci_disconnect_all(); 1339 } 1340 1341 // update discoverable mode 1342 gap_discoverable_control(clients_require_discoverable()); 1343 // start power off, if last active client 1344 if (!clients_require_power_on()){ 1345 start_power_off_timer(); 1346 } 1347 break; 1348 default: 1349 break; 1350 } 1351 break; 1352 } 1353 if (err) { 1354 log_info("Daemon Handler: err %d\n", err); 1355 } 1356 return err; 1357 } 1358 1359 1360 static void daemon_set_logging_enabled(int enabled){ 1361 if (enabled && !loggingEnabled){ 1362 // construct path to log file 1363 switch (BTSTACK_LOG_TYPE){ 1364 case HCI_DUMP_STDOUT: 1365 snprintf(string_buffer, sizeof(string_buffer), "stdout"); 1366 break; 1367 case HCI_DUMP_PACKETLOGGER: 1368 snprintf(string_buffer, sizeof(string_buffer), "%s/hci_dump.pklg", btstack_server_storage_path); 1369 break; 1370 case HCI_DUMP_BLUEZ: 1371 snprintf(string_buffer, sizeof(string_buffer), "%s/hci_dump.snoop", btstack_server_storage_path); 1372 break; 1373 default: 1374 break; 1375 } 1376 hci_dump_open(string_buffer, BTSTACK_LOG_TYPE); 1377 printf("Logging to %s\n", string_buffer); 1378 } 1379 if (!enabled && loggingEnabled){ 1380 hci_dump_close(); 1381 } 1382 loggingEnabled = enabled; 1383 } 1384 1385 // local cache used to manage UI status 1386 static HCI_STATE hci_state = HCI_STATE_OFF; 1387 static int num_connections = 0; 1388 static void update_ui_status(void){ 1389 if (hci_state != HCI_STATE_WORKING) { 1390 bluetooth_status_handler(BLUETOOTH_OFF); 1391 } else { 1392 if (num_connections) { 1393 bluetooth_status_handler(BLUETOOTH_ACTIVE); 1394 } else { 1395 bluetooth_status_handler(BLUETOOTH_ON); 1396 } 1397 } 1398 } 1399 1400 #ifdef USE_SPRINGBOARD 1401 static void preferences_changed_callback(void){ 1402 int logging = platform_iphone_logging_enabled(); 1403 log_info("Logging enabled: %u\n", logging); 1404 daemon_set_logging_enabled(logging); 1405 } 1406 #endif 1407 1408 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){ 1409 1410 uint8_t update_status = 0; 1411 1412 // handle state event 1413 switch (hci_event_packet_get_type(packet)) { 1414 case BTSTACK_EVENT_STATE: 1415 hci_state = packet[2]; 1416 log_info("New state: %u\n", hci_state); 1417 update_status = 1; 1418 break; 1419 case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED: 1420 num_connections = packet[2]; 1421 log_info("New nr connections: %u\n", num_connections); 1422 update_status = 1; 1423 break; 1424 default: 1425 break; 1426 } 1427 1428 // choose full bluetooth state 1429 if (update_status) { 1430 update_ui_status(); 1431 } 1432 } 1433 1434 static void daemon_retry_parked(void){ 1435 1436 // socket_connection_retry_parked is not reentrant 1437 static int retry_mutex = 0; 1438 1439 // lock mutex 1440 if (retry_mutex) return; 1441 retry_mutex = 1; 1442 1443 // ... try sending again 1444 socket_connection_retry_parked(); 1445 1446 // unlock mutex 1447 retry_mutex = 0; 1448 } 1449 1450 static void daemon_emit_packet(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1451 if (connection) { 1452 socket_connection_send_packet(connection, packet_type, channel, packet, size); 1453 } else { 1454 socket_connection_send_packet_all(packet_type, channel, packet, size); 1455 } 1456 } 1457 1458 static uint8_t remote_name_event[2+1+6+DEVICE_NAME_LEN+1]; // +1 for \0 in log_info 1459 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1460 uint16_t cid; 1461 int i; 1462 bd_addr_t addr; 1463 switch (packet_type) { 1464 case HCI_EVENT_PACKET: 1465 deamon_status_event_handler(packet, size); 1466 switch (hci_event_packet_get_type(packet)){ 1467 1468 case BTSTACK_EVENT_STATE: 1469 if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break; 1470 if (tlv_setup_done) break; 1471 1472 // setup TLV using local address as part of the name 1473 gap_local_bd_addr(addr); 1474 log_info("BTstack up and running at %s", bd_addr_to_str(addr)); 1475 snprintf(string_buffer, sizeof(string_buffer), "%s/btstack_%s.tlv", btstack_server_storage_path, bd_addr_to_str(addr)); 1476 tlv_impl = btstack_tlv_posix_init_instance(&tlv_context, string_buffer); 1477 btstack_tlv_set_instance(tlv_impl, &tlv_context); 1478 1479 // setup link key db 1480 hci_set_link_key_db(btstack_link_key_db_tlv_get_instance(tlv_impl, &tlv_context)); 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_DEVICE_NAME_DB_INSTANCE 1962 btstack_device_name_db = BTSTACK_DEVICE_NAME_DB_INSTANCE(); 1963 #endif 1964 1965 #ifdef _WIN32 1966 btstack_run_loop_init(btstack_run_loop_windows_get_instance()); 1967 #else 1968 btstack_run_loop_init(btstack_run_loop_posix_get_instance()); 1969 #endif 1970 1971 // init power management notifications 1972 if (control && control->register_for_power_notifications){ 1973 control->register_for_power_notifications(power_notification_callback); 1974 } 1975 1976 // logging 1977 loggingEnabled = 0; 1978 int newLoggingEnabled = 1; 1979 #ifdef HAVE_PLATFORM_IPHONE_OS 1980 // iPhone has toggle in Preferences.app 1981 newLoggingEnabled = platform_iphone_logging_enabled(); 1982 #endif 1983 daemon_set_logging_enabled(newLoggingEnabled); 1984 1985 // dump version 1986 log_info("BTStack Server started\n"); 1987 log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE); 1988 1989 // init HCI 1990 hci_init(transport, config); 1991 if (btstack_link_key_db){ 1992 hci_set_link_key_db(btstack_link_key_db); 1993 } 1994 if (control){ 1995 hci_set_control(control); 1996 } 1997 1998 // hostname for POSIX systems 1999 gethostname(hostname, 30); 2000 hostname[29] = '\0'; 2001 gap_set_local_name(hostname); 2002 2003 #ifdef HAVE_PLATFORM_IPHONE_OS 2004 // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option 2005 gap_ssp_set_enable(0); 2006 #endif 2007 2008 // register for HCI events 2009 hci_event_callback_registration.callback = &stack_packet_handler; 2010 hci_add_event_handler(&hci_event_callback_registration); 2011 2012 // init L2CAP 2013 l2cap_init(); 2014 l2cap_register_packet_handler(&stack_packet_handler); 2015 timeout.process = daemon_no_connections_timeout; 2016 2017 #ifdef ENABLE_RFCOMM 2018 log_info("config.h: ENABLE_RFCOMM\n"); 2019 rfcomm_init(); 2020 #endif 2021 2022 #ifdef ENABLE_SDP 2023 sdp_init(); 2024 #endif 2025 2026 #ifdef ENABLE_BLE 2027 sm_init(); 2028 sm_event_callback_registration.callback = &stack_packet_handler; 2029 sm_add_event_handler(&sm_event_callback_registration); 2030 // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY); 2031 // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION); 2032 2033 // GATT Client 2034 gatt_client_init(); 2035 2036 // GATT Server - empty attribute database 2037 att_server_init(NULL, NULL, NULL); 2038 2039 #endif 2040 2041 #ifdef USE_LAUNCHD 2042 socket_connection_create_launchd(); 2043 #else 2044 // create server 2045 if (tcp_flag) { 2046 socket_connection_create_tcp(BTSTACK_PORT); 2047 } else { 2048 #ifdef HAVE_UNIX_SOCKETS 2049 socket_connection_create_unix(BTSTACK_UNIX); 2050 #endif 2051 } 2052 #endif 2053 socket_connection_register_packet_callback(&daemon_client_handler); 2054 2055 #ifdef HAVE_PLATFORM_IPHONE_OS 2056 // notify daemons 2057 notify_post("ch.ringwald.btstack.started"); 2058 2059 // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop 2060 pthread_t run_loop; 2061 pthread_create(&run_loop, NULL, &btstack_run_loop_thread, NULL); 2062 2063 // needed to receive notifications 2064 CFRunLoopRun(); 2065 #endif 2066 // go! 2067 btstack_run_loop_execute(); 2068 return 0; 2069 } 2070 2071 int btstack_server_run_tcp(void){ 2072 return btstack_server_run(1); 2073 } 2074 2075 int main (int argc, char * const * argv){ 2076 2077 int tcp_flag = 0; 2078 struct option long_options[] = { 2079 { "tcp", no_argument, &tcp_flag, 1 }, 2080 { "help", no_argument, 0, 0 }, 2081 { 0,0,0,0 } // This is a filler for -1 2082 }; 2083 2084 while (1) { 2085 int c; 2086 int option_index = -1; 2087 c = getopt_long(argc, argv, "h", long_options, &option_index); 2088 if (c == -1) break; // no more option 2089 2090 // treat long parameter first 2091 if (option_index == -1) { 2092 switch (c) { 2093 case '?': 2094 case 'h': 2095 usage(argv[0]); 2096 return 0; 2097 break; 2098 } 2099 } else { 2100 switch (option_index) { 2101 case 1: 2102 usage(argv[0]); 2103 return 0; 2104 break; 2105 } 2106 } 2107 } 2108 2109 #ifndef HAVE_UNIX_SOCKETS 2110 // TCP is default if there are no unix sockets 2111 tcp_flag = 1; 2112 #endif 2113 2114 btstack_server_run(tcp_flag); 2115 } 2116 2117 void btstack_server_set_storage_path(const char * path){ 2118 if (btstack_server_storage_path){ 2119 free((void*)btstack_server_storage_path); 2120 btstack_server_storage_path = NULL; 2121 } 2122 btstack_server_storage_path = strdup(path); 2123 log_info("Storage path %s", btstack_server_storage_path); 2124 } 2125