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