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