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 gatt_client_write_client_characteristic_configuration(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic, configuration); 1259 break; 1260 case GATT_GET_MTU: 1261 handle = little_endian_read_16(packet, 3); 1262 gatt_client_get_mtu(handle, &mtu); 1263 send_gatt_mtu_event(connection, handle, mtu); 1264 break; 1265 } 1266 #endif 1267 #ifdef ENABLE_BLE 1268 case SM_SET_AUTHENTICATION_REQUIREMENTS: 1269 log_info("set auth %x", packet[3]); 1270 sm_set_authentication_requirements(packet[3]); 1271 break; 1272 case SM_SET_IO_CAPABILITIES: 1273 log_info("set io %x", packet[3]); 1274 sm_set_io_capabilities(packet[3]); 1275 break; 1276 case SM_BONDING_DECLINE: 1277 sm_bonding_decline(little_endian_read_16(packet, 3)); 1278 break; 1279 case SM_JUST_WORKS_CONFIRM: 1280 sm_just_works_confirm(little_endian_read_16(packet, 3)); 1281 break; 1282 case SM_NUMERIC_COMPARISON_CONFIRM: 1283 sm_numeric_comparison_confirm(little_endian_read_16(packet, 3)); 1284 break; 1285 case SM_PASSKEY_INPUT: 1286 sm_passkey_input(little_endian_read_16(packet, 3), little_endian_read_32(packet, 5)); 1287 break; 1288 #endif 1289 default: 1290 log_error("Error: command %u not implemented:", READ_CMD_OCF(packet)); 1291 break; 1292 } 1293 1294 return 0; 1295 } 1296 1297 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){ 1298 1299 int err = 0; 1300 client_state_t * client; 1301 1302 switch (packet_type){ 1303 case HCI_COMMAND_DATA_PACKET: 1304 if (READ_CMD_OGF(data) != OGF_BTSTACK) { 1305 // HCI Command 1306 hci_send_cmd_packet(data, length); 1307 } else { 1308 // BTstack command 1309 btstack_command_handler(connection, data, length); 1310 } 1311 break; 1312 case L2CAP_DATA_PACKET: 1313 // process l2cap packet... 1314 err = l2cap_send(channel, data, length); 1315 break; 1316 case RFCOMM_DATA_PACKET: 1317 // process l2cap packet... 1318 err = rfcomm_send(channel, data, length); 1319 break; 1320 case DAEMON_EVENT_PACKET: 1321 switch (data[0]) { 1322 case DAEMON_EVENT_CONNECTION_OPENED: 1323 log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection); 1324 1325 client = calloc(sizeof(client_state_t), 1); 1326 if (!client) break; // fail 1327 client->connection = connection; 1328 client->power_mode = HCI_POWER_OFF; 1329 client->discoverable = 0; 1330 btstack_linked_list_add(&clients, (btstack_linked_item_t *) client); 1331 break; 1332 case DAEMON_EVENT_CONNECTION_CLOSED: 1333 log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection); 1334 daemon_disconnect_client(connection); 1335 // no clients -> no HCI connections 1336 if (!clients){ 1337 hci_disconnect_all(); 1338 } 1339 1340 // update discoverable mode 1341 gap_discoverable_control(clients_require_discoverable()); 1342 // start power off, if last active client 1343 if (!clients_require_power_on()){ 1344 start_power_off_timer(); 1345 } 1346 break; 1347 default: 1348 break; 1349 } 1350 break; 1351 } 1352 if (err) { 1353 log_info("Daemon Handler: err %d\n", err); 1354 } 1355 return err; 1356 } 1357 1358 1359 static void daemon_set_logging_enabled(int enabled){ 1360 if (enabled && !loggingEnabled){ 1361 // construct path to log file 1362 switch (BTSTACK_LOG_TYPE){ 1363 case HCI_DUMP_STDOUT: 1364 snprintf(string_buffer, sizeof(string_buffer), "stdout"); 1365 break; 1366 case HCI_DUMP_PACKETLOGGER: 1367 snprintf(string_buffer, sizeof(string_buffer), "%s/hci_dump.pklg", btstack_server_storage_path); 1368 break; 1369 case HCI_DUMP_BLUEZ: 1370 snprintf(string_buffer, sizeof(string_buffer), "%s/hci_dump.snoop", btstack_server_storage_path); 1371 break; 1372 default: 1373 break; 1374 } 1375 hci_dump_open(string_buffer, BTSTACK_LOG_TYPE); 1376 printf("Logging to %s\n", string_buffer); 1377 } 1378 if (!enabled && loggingEnabled){ 1379 hci_dump_close(); 1380 } 1381 loggingEnabled = enabled; 1382 } 1383 1384 // local cache used to manage UI status 1385 static HCI_STATE hci_state = HCI_STATE_OFF; 1386 static int num_connections = 0; 1387 static void update_ui_status(void){ 1388 if (hci_state != HCI_STATE_WORKING) { 1389 bluetooth_status_handler(BLUETOOTH_OFF); 1390 } else { 1391 if (num_connections) { 1392 bluetooth_status_handler(BLUETOOTH_ACTIVE); 1393 } else { 1394 bluetooth_status_handler(BLUETOOTH_ON); 1395 } 1396 } 1397 } 1398 1399 #ifdef USE_SPRINGBOARD 1400 static void preferences_changed_callback(void){ 1401 int logging = platform_iphone_logging_enabled(); 1402 log_info("Logging enabled: %u\n", logging); 1403 daemon_set_logging_enabled(logging); 1404 } 1405 #endif 1406 1407 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){ 1408 1409 uint8_t update_status = 0; 1410 1411 // handle state event 1412 switch (hci_event_packet_get_type(packet)) { 1413 case BTSTACK_EVENT_STATE: 1414 hci_state = packet[2]; 1415 log_info("New state: %u\n", hci_state); 1416 update_status = 1; 1417 break; 1418 case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED: 1419 num_connections = packet[2]; 1420 log_info("New nr connections: %u\n", num_connections); 1421 update_status = 1; 1422 break; 1423 default: 1424 break; 1425 } 1426 1427 // choose full bluetooth state 1428 if (update_status) { 1429 update_ui_status(); 1430 } 1431 } 1432 1433 static void daemon_retry_parked(void){ 1434 1435 // socket_connection_retry_parked is not reentrant 1436 static int retry_mutex = 0; 1437 1438 // lock mutex 1439 if (retry_mutex) return; 1440 retry_mutex = 1; 1441 1442 // ... try sending again 1443 socket_connection_retry_parked(); 1444 1445 // unlock mutex 1446 retry_mutex = 0; 1447 } 1448 1449 static void daemon_emit_packet(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1450 if (connection) { 1451 socket_connection_send_packet(connection, packet_type, channel, packet, size); 1452 } else { 1453 socket_connection_send_packet_all(packet_type, channel, packet, size); 1454 } 1455 } 1456 1457 // copy from btstack_util, just using a '-' 1458 static char bd_addr_to_str_buffer[6*3]; // 12:45:78:01:34:67\0 1459 char * bd_addr_to_str_dashed(const bd_addr_t addr){ 1460 // orig code 1461 // sprintf(bd_addr_to_str_buffer, "%02x:%02x:%02x:%02x:%02x:%02x", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); 1462 // sprintf-free code 1463 char * p = bd_addr_to_str_buffer; 1464 int i; 1465 for (i = 0; i < 6 ; i++) { 1466 uint8_t byte = addr[i]; 1467 *p++ = char_for_nibble(byte >> 4); 1468 *p++ = char_for_nibble(byte & 0x0f); 1469 *p++ = '-'; 1470 } 1471 *--p = 0; 1472 return (char *) bd_addr_to_str_buffer; 1473 } 1474 1475 static uint8_t remote_name_event[2+1+6+DEVICE_NAME_LEN+1]; // +1 for \0 in log_info 1476 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1477 uint16_t cid; 1478 int i; 1479 bd_addr_t addr; 1480 switch (packet_type) { 1481 case HCI_EVENT_PACKET: 1482 deamon_status_event_handler(packet, size); 1483 switch (hci_event_packet_get_type(packet)){ 1484 1485 case BTSTACK_EVENT_STATE: 1486 if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break; 1487 if (tlv_setup_done) break; 1488 1489 // setup TLV using local address as part of the name 1490 gap_local_bd_addr(addr); 1491 log_info("BTstack up and running at %s", bd_addr_to_str(addr)); 1492 snprintf(string_buffer, sizeof(string_buffer), "%s/btstack_%s.tlv", btstack_server_storage_path, bd_addr_to_str_dashed(addr)); 1493 tlv_impl = btstack_tlv_posix_init_instance(&tlv_context, string_buffer); 1494 btstack_tlv_set_instance(tlv_impl, &tlv_context); 1495 1496 // setup link key db 1497 hci_set_link_key_db(btstack_link_key_db_tlv_get_instance(tlv_impl, &tlv_context)); 1498 1499 // init le device db to use TLV 1500 le_device_db_tlv_configure(tlv_impl, &tlv_context); 1501 le_device_db_init(); 1502 le_device_db_set_local_bd_addr(addr); 1503 1504 tlv_setup_done = 1; 1505 break; 1506 1507 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 1508 // ACL buffer freed... 1509 daemon_retry_parked(); 1510 // no need to tell clients 1511 return; 1512 1513 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 1514 if (!btstack_device_name_db) break; 1515 if (packet[2]) break; // status not ok 1516 1517 reverse_bd_addr(&packet[3], addr); 1518 // fix for invalid remote names - terminate on 0xff 1519 for (i=0; i<248;i++){ 1520 if (packet[9+i] == 0xff){ 1521 packet[9+i] = 0; 1522 break; 1523 } 1524 } 1525 packet[9+248] = 0; 1526 btstack_device_name_db->put_name(addr, (device_name_t *)&packet[9]); 1527 break; 1528 1529 case HCI_EVENT_INQUIRY_RESULT: 1530 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{ 1531 if (!btstack_device_name_db) break; 1532 1533 // first send inq result packet 1534 daemon_emit_packet(connection, packet_type, channel, packet, size); 1535 1536 // then send cached remote names 1537 int offset = 3; 1538 for (i=0; i<packet[2];i++){ 1539 reverse_bd_addr(&packet[offset], addr); 1540 if (btstack_device_name_db->get_name(addr, (device_name_t *) &remote_name_event[9])){ 1541 remote_name_event[0] = DAEMON_EVENT_REMOTE_NAME_CACHED; 1542 remote_name_event[1] = sizeof(remote_name_event) - 2 - 1; 1543 remote_name_event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 1544 reverse_bd_addr(addr, &remote_name_event[3]); 1545 1546 remote_name_event[9+248] = 0; // assert \0 for log_info 1547 log_info("DAEMON_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(addr), &remote_name_event[9]); 1548 hci_dump_packet(HCI_EVENT_PACKET, 0, remote_name_event, sizeof(remote_name_event)-1); 1549 daemon_emit_packet(connection, HCI_EVENT_PACKET, channel, remote_name_event, sizeof(remote_name_event) -1); 1550 } 1551 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2; 1552 } 1553 return; 1554 } 1555 1556 case DAEMON_EVENT_RFCOMM_CREDITS: 1557 // RFCOMM CREDITS received... 1558 daemon_retry_parked(); 1559 break; 1560 1561 case RFCOMM_EVENT_CHANNEL_OPENED: 1562 cid = little_endian_read_16(packet, 13); 1563 connection = connection_for_rfcomm_cid(cid); 1564 if (!connection) break; 1565 if (packet[2]) { 1566 daemon_remove_client_rfcomm_channel(connection, cid); 1567 } else { 1568 daemon_add_client_rfcomm_channel(connection, cid); 1569 } 1570 break; 1571 case RFCOMM_EVENT_CHANNEL_CLOSED: 1572 cid = little_endian_read_16(packet, 2); 1573 connection = connection_for_rfcomm_cid(cid); 1574 if (!connection) break; 1575 daemon_remove_client_rfcomm_channel(connection, cid); 1576 break; 1577 case DAEMON_EVENT_RFCOMM_SERVICE_REGISTERED: 1578 if (packet[2]) break; 1579 daemon_add_client_rfcomm_service(connection, packet[3]); 1580 break; 1581 case L2CAP_EVENT_CHANNEL_OPENED: 1582 cid = little_endian_read_16(packet, 13); 1583 connection = connection_for_l2cap_cid(cid); 1584 if (!connection) break; 1585 if (packet[2]) { 1586 daemon_remove_client_l2cap_channel(connection, cid); 1587 } else { 1588 daemon_add_client_l2cap_channel(connection, cid); 1589 } 1590 break; 1591 case L2CAP_EVENT_CHANNEL_CLOSED: 1592 cid = little_endian_read_16(packet, 2); 1593 connection = connection_for_l2cap_cid(cid); 1594 if (!connection) break; 1595 daemon_remove_client_l2cap_channel(connection, cid); 1596 break; 1597 #if defined(ENABLE_BLE) && defined(HAVE_MALLOC) 1598 case HCI_EVENT_DISCONNECTION_COMPLETE: 1599 log_info("daemon : ignore HCI_EVENT_DISCONNECTION_COMPLETE ingnoring."); 1600 // note: moved to gatt_client_handler because it's received here prematurely 1601 // daemon_remove_gatt_client_helper(little_endian_read_16(packet, 3)); 1602 break; 1603 #endif 1604 default: 1605 break; 1606 } 1607 break; 1608 case L2CAP_DATA_PACKET: 1609 connection = connection_for_l2cap_cid(channel); 1610 if (!connection) return; 1611 break; 1612 case RFCOMM_DATA_PACKET: 1613 connection = connection_for_l2cap_cid(channel); 1614 if (!connection) return; 1615 break; 1616 default: 1617 break; 1618 } 1619 1620 daemon_emit_packet(connection, packet_type, channel, packet, size); 1621 } 1622 1623 static void stack_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1624 daemon_packet_handler(NULL, packet_type, channel, packet, size); 1625 } 1626 1627 static void handle_sdp_rfcomm_service_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1628 switch (hci_event_packet_get_type(packet)){ 1629 case SDP_EVENT_QUERY_RFCOMM_SERVICE: 1630 case SDP_EVENT_QUERY_COMPLETE: 1631 // already HCI Events, just forward them 1632 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1633 socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, packet, size); 1634 break; 1635 default: 1636 break; 1637 } 1638 } 1639 1640 static void sdp_client_assert_buffer(int size){ 1641 if (size > attribute_value_buffer_size){ 1642 log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size); 1643 } 1644 } 1645 1646 // define new packet type SDP_CLIENT_PACKET 1647 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1648 int event_len; 1649 1650 switch (hci_event_packet_get_type(packet)){ 1651 case SDP_EVENT_QUERY_ATTRIBUTE_BYTE: 1652 sdp_client_assert_buffer(sdp_event_query_attribute_byte_get_attribute_length(packet)); 1653 attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet); 1654 if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)){ 1655 log_info_hexdump(attribute_value, sdp_event_query_attribute_byte_get_attribute_length(packet)); 1656 1657 int event_len = 1 + 3 * 2 + sdp_event_query_attribute_byte_get_attribute_length(packet); 1658 uint8_t event[event_len]; 1659 event[0] = SDP_EVENT_QUERY_ATTRIBUTE_VALUE; 1660 little_endian_store_16(event, 1, sdp_event_query_attribute_byte_get_record_id(packet)); 1661 little_endian_store_16(event, 3, sdp_event_query_attribute_byte_get_attribute_id(packet)); 1662 little_endian_store_16(event, 5, (uint16_t)sdp_event_query_attribute_byte_get_attribute_length(packet)); 1663 memcpy(&event[7], attribute_value, sdp_event_query_attribute_byte_get_attribute_length(packet)); 1664 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len); 1665 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len); 1666 } 1667 break; 1668 case SDP_EVENT_QUERY_COMPLETE: 1669 event_len = packet[1] + 2; 1670 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, event_len); 1671 socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, packet, event_len); 1672 break; 1673 } 1674 } 1675 1676 static void power_notification_callback(POWER_NOTIFICATION_t notification){ 1677 switch (notification) { 1678 case POWER_WILL_SLEEP: 1679 // let's sleep 1680 power_management_sleep = 1; 1681 hci_power_control(HCI_POWER_SLEEP); 1682 break; 1683 case POWER_WILL_WAKE_UP: 1684 // assume that all clients use Bluetooth -> if connection, start Bluetooth 1685 power_management_sleep = 0; 1686 if (clients_require_power_on()) { 1687 hci_power_control(HCI_POWER_ON); 1688 } 1689 break; 1690 default: 1691 break; 1692 } 1693 } 1694 1695 static void daemon_sigint_handler(int param){ 1696 1697 #ifdef HAVE_PLATFORM_IPHONE_OS 1698 // notify daemons 1699 notify_post("ch.ringwald.btstack.stopped"); 1700 #endif 1701 1702 log_info(" <= SIGINT received, shutting down..\n"); 1703 1704 hci_power_control( HCI_POWER_OFF); 1705 hci_close(); 1706 1707 log_info("Good bye, see you.\n"); 1708 1709 exit(0); 1710 } 1711 1712 // MARK: manage power off timer 1713 1714 #define USE_POWER_OFF_TIMER 1715 1716 static void stop_power_off_timer(void){ 1717 #ifdef USE_POWER_OFF_TIMER 1718 if (timeout_active) { 1719 btstack_run_loop_remove_timer(&timeout); 1720 timeout_active = 0; 1721 } 1722 #endif 1723 } 1724 1725 static void start_power_off_timer(void){ 1726 #ifdef USE_POWER_OFF_TIMER 1727 stop_power_off_timer(); 1728 btstack_run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT); 1729 btstack_run_loop_add_timer(&timeout); 1730 timeout_active = 1; 1731 #else 1732 hci_power_control(HCI_POWER_OFF); 1733 #endif 1734 } 1735 1736 // MARK: manage list of clients 1737 1738 1739 static client_state_t * client_for_connection(connection_t *connection) { 1740 btstack_linked_item_t *it; 1741 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1742 client_state_t * client_state = (client_state_t *) it; 1743 if (client_state->connection == connection) { 1744 return client_state; 1745 } 1746 } 1747 return NULL; 1748 } 1749 1750 static void clients_clear_power_request(void){ 1751 btstack_linked_item_t *it; 1752 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1753 client_state_t * client_state = (client_state_t *) it; 1754 client_state->power_mode = HCI_POWER_OFF; 1755 } 1756 } 1757 1758 static int clients_require_power_on(void){ 1759 1760 if (global_enable) return 1; 1761 1762 btstack_linked_item_t *it; 1763 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1764 client_state_t * client_state = (client_state_t *) it; 1765 if (client_state->power_mode == HCI_POWER_ON) { 1766 return 1; 1767 } 1768 } 1769 return 0; 1770 } 1771 1772 static int clients_require_discoverable(void){ 1773 btstack_linked_item_t *it; 1774 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1775 client_state_t * client_state = (client_state_t *) it; 1776 if (client_state->discoverable) { 1777 return 1; 1778 } 1779 } 1780 return 0; 1781 } 1782 1783 static void usage(const char * name) { 1784 printf("%s, BTstack background daemon\n", name); 1785 printf("usage: %s [--help] [--tcp]\n", name); 1786 printf(" --help display this usage\n"); 1787 printf(" --tcp use TCP server on port %u\n", BTSTACK_PORT); 1788 printf("Without the --tcp option, BTstack Server is listening on unix domain socket %s\n\n", BTSTACK_UNIX); 1789 } 1790 1791 #ifdef HAVE_PLATFORM_IPHONE_OS 1792 static void * btstack_run_loop_thread(void *context){ 1793 btstack_run_loop_execute(); 1794 return NULL; 1795 } 1796 #endif 1797 1798 #ifdef ENABLE_BLE 1799 1800 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1801 1802 // hack: handle disconnection_complete_here instead of main hci event packet handler 1803 // we receive a HCI event packet in disguise 1804 if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){ 1805 log_info("daemon hack: handle disconnection_complete in handle_gatt_client_event instead of main hci event packet handler"); 1806 hci_con_handle_t con_handle = little_endian_read_16(packet, 3); 1807 daemon_remove_gatt_client_helper(con_handle); 1808 return; 1809 } 1810 1811 // only handle GATT Events 1812 switch(hci_event_packet_get_type(packet)){ 1813 case GATT_EVENT_SERVICE_QUERY_RESULT: 1814 case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT: 1815 case GATT_EVENT_NOTIFICATION: 1816 case GATT_EVENT_INDICATION: 1817 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT: 1818 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT: 1819 case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1820 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1821 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT: 1822 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT: 1823 case GATT_EVENT_QUERY_COMPLETE: 1824 break; 1825 default: 1826 return; 1827 } 1828 1829 hci_con_handle_t con_handle = little_endian_read_16(packet, 2); 1830 btstack_linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle); 1831 if (!gatt_client_helper){ 1832 log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle); 1833 return; 1834 } 1835 1836 connection_t *connection = NULL; 1837 1838 // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections 1839 switch(hci_event_packet_get_type(packet)){ 1840 case GATT_EVENT_NOTIFICATION: 1841 case GATT_EVENT_INDICATION:{ 1842 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1843 1844 btstack_linked_item_t *it; 1845 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1846 client_state_t * client_state = (client_state_t *) it; 1847 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size); 1848 } 1849 return; 1850 } 1851 default: 1852 break; 1853 } 1854 1855 // otherwise, we have to have an active connection 1856 connection = gatt_client_helper->active_connection; 1857 uint16_t offset; 1858 uint16_t length; 1859 1860 if (!connection) return; 1861 1862 switch(hci_event_packet_get_type(packet)){ 1863 1864 case GATT_EVENT_SERVICE_QUERY_RESULT: 1865 case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT: 1866 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT: 1867 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT: 1868 case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1869 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT: 1870 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1871 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size); 1872 break; 1873 1874 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT: 1875 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1876 offset = little_endian_read_16(packet, 6); 1877 length = little_endian_read_16(packet, 8); 1878 gatt_client_helper->characteristic_buffer[0] = hci_event_packet_get_type(packet); // store type (characteristic/descriptor) 1879 gatt_client_helper->characteristic_handle = little_endian_read_16(packet, 4); // store attribute handle 1880 gatt_client_helper->characteristic_length = offset + length; // update length 1881 memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length); 1882 break; 1883 1884 case GATT_EVENT_QUERY_COMPLETE:{ 1885 gatt_client_helper->active_connection = NULL; 1886 if (gatt_client_helper->characteristic_length){ 1887 // send re-combined long characteristic value or long characteristic descriptor value 1888 uint8_t * event = gatt_client_helper->characteristic_buffer; 1889 uint16_t event_size = 10 + gatt_client_helper->characteristic_length; 1890 // event[0] == already set by previsous case 1891 event[1] = 8 + gatt_client_helper->characteristic_length; 1892 little_endian_store_16(event, 2, little_endian_read_16(packet, 2)); 1893 little_endian_store_16(event, 4, gatt_client_helper->characteristic_handle); 1894 little_endian_store_16(event, 6, 0); // offset 1895 little_endian_store_16(event, 8, gatt_client_helper->characteristic_length); 1896 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size); 1897 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size); 1898 gatt_client_helper->characteristic_length = 0; 1899 } 1900 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1901 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size); 1902 break; 1903 } 1904 default: 1905 break; 1906 } 1907 } 1908 #endif 1909 1910 static char hostname[30]; 1911 1912 int btstack_server_run(int tcp_flag){ 1913 1914 if (tcp_flag){ 1915 printf("BTstack Server started on port %u\n", BTSTACK_PORT); 1916 } else { 1917 printf("BTstack Server started on socket %s\n", BTSTACK_UNIX); 1918 } 1919 1920 // handle default init 1921 if (!btstack_server_storage_path){ 1922 #ifdef _WIN32 1923 btstack_server_storage_path = strdup("."); 1924 #else 1925 btstack_server_storage_path = strdup("/tmp"); 1926 #endif 1927 } 1928 1929 // make stdout unbuffered 1930 setbuf(stdout, NULL); 1931 1932 // handle CTRL-c 1933 signal(SIGINT, daemon_sigint_handler); 1934 // handle SIGTERM - suggested for launchd 1935 signal(SIGTERM, daemon_sigint_handler); 1936 1937 socket_connection_init(); 1938 1939 btstack_control_t * control = NULL; 1940 void * config = NULL; 1941 const btstack_uart_block_t * uart_block_implementation = NULL; 1942 (void) uart_block_implementation; 1943 1944 #ifdef HAVE_TRANSPORT_H4 1945 hci_transport_config_uart.type = HCI_TRANSPORT_CONFIG_UART; 1946 hci_transport_config_uart.baudrate_init = UART_SPEED; 1947 hci_transport_config_uart.baudrate_main = 0; 1948 hci_transport_config_uart.flowcontrol = 1; 1949 hci_transport_config_uart.device_name = UART_DEVICE; 1950 1951 #ifndef HAVE_PLATFORM_IPHONE_OS 1952 #ifdef _WIN32 1953 uart_block_implementation = btstack_uart_block_windows_instance(); 1954 #else 1955 uart_block_implementation = btstack_uart_block_posix_instance(); 1956 #endif 1957 #endif 1958 1959 #ifdef HAVE_PLATFORM_IPHONE_OS 1960 // use default (max) UART baudrate over netgraph interface 1961 hci_transport_config_uart.baudrate_init = 0; 1962 #endif 1963 1964 config = &hci_transport_config_uart; 1965 transport = hci_transport_h4_instance(uart_block_implementation); 1966 #endif 1967 1968 #ifdef HAVE_TRANSPORT_USB 1969 transport = hci_transport_usb_instance(); 1970 #endif 1971 1972 #ifdef HAVE_PLATFORM_IPHONE_OS 1973 control = &btstack_control_iphone; 1974 if (btstack_control_iphone_power_management_supported()){ 1975 hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake"); 1976 } 1977 bluetooth_status_handler = platform_iphone_status_handler; 1978 platform_iphone_register_window_manager_restart(update_ui_status); 1979 platform_iphone_register_preferences_changed(preferences_changed_callback); 1980 #endif 1981 1982 #ifdef BTSTACK_DEVICE_NAME_DB_INSTANCE 1983 btstack_device_name_db = BTSTACK_DEVICE_NAME_DB_INSTANCE(); 1984 #endif 1985 1986 #ifdef _WIN32 1987 btstack_run_loop_init(btstack_run_loop_windows_get_instance()); 1988 #else 1989 btstack_run_loop_init(btstack_run_loop_posix_get_instance()); 1990 #endif 1991 1992 // init power management notifications 1993 if (control && control->register_for_power_notifications){ 1994 control->register_for_power_notifications(power_notification_callback); 1995 } 1996 1997 // logging 1998 loggingEnabled = 0; 1999 int newLoggingEnabled = 1; 2000 #ifdef HAVE_PLATFORM_IPHONE_OS 2001 // iPhone has toggle in Preferences.app 2002 newLoggingEnabled = platform_iphone_logging_enabled(); 2003 #endif 2004 daemon_set_logging_enabled(newLoggingEnabled); 2005 2006 // dump version 2007 log_info("BTStack Server started\n"); 2008 log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE); 2009 2010 // init HCI 2011 hci_init(transport, config); 2012 if (btstack_link_key_db){ 2013 hci_set_link_key_db(btstack_link_key_db); 2014 } 2015 if (control){ 2016 hci_set_control(control); 2017 } 2018 2019 // hostname for POSIX systems 2020 gethostname(hostname, 30); 2021 hostname[29] = '\0'; 2022 gap_set_local_name(hostname); 2023 2024 #ifdef HAVE_PLATFORM_IPHONE_OS 2025 // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option 2026 gap_ssp_set_enable(0); 2027 #endif 2028 2029 // register for HCI events 2030 hci_event_callback_registration.callback = &stack_packet_handler; 2031 hci_add_event_handler(&hci_event_callback_registration); 2032 2033 // init L2CAP 2034 l2cap_init(); 2035 l2cap_register_packet_handler(&stack_packet_handler); 2036 timeout.process = daemon_no_connections_timeout; 2037 2038 #ifdef ENABLE_RFCOMM 2039 log_info("config.h: ENABLE_RFCOMM\n"); 2040 rfcomm_init(); 2041 #endif 2042 2043 #ifdef ENABLE_SDP 2044 sdp_init(); 2045 #endif 2046 2047 #ifdef ENABLE_BLE 2048 sm_init(); 2049 sm_event_callback_registration.callback = &stack_packet_handler; 2050 sm_add_event_handler(&sm_event_callback_registration); 2051 // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY); 2052 // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION); 2053 2054 // GATT Client 2055 gatt_client_init(); 2056 2057 // GATT Server - empty attribute database 2058 att_server_init(NULL, NULL, NULL); 2059 2060 #endif 2061 2062 #ifdef USE_LAUNCHD 2063 socket_connection_create_launchd(); 2064 #else 2065 // create server 2066 if (tcp_flag) { 2067 socket_connection_create_tcp(BTSTACK_PORT); 2068 } else { 2069 #ifdef HAVE_UNIX_SOCKETS 2070 socket_connection_create_unix(BTSTACK_UNIX); 2071 #endif 2072 } 2073 #endif 2074 socket_connection_register_packet_callback(&daemon_client_handler); 2075 2076 #ifdef HAVE_PLATFORM_IPHONE_OS 2077 // notify daemons 2078 notify_post("ch.ringwald.btstack.started"); 2079 2080 // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop 2081 pthread_t run_loop; 2082 pthread_create(&run_loop, NULL, &btstack_run_loop_thread, NULL); 2083 2084 // needed to receive notifications 2085 CFRunLoopRun(); 2086 #endif 2087 // go! 2088 btstack_run_loop_execute(); 2089 return 0; 2090 } 2091 2092 int btstack_server_run_tcp(void){ 2093 return btstack_server_run(1); 2094 } 2095 2096 int main (int argc, char * const * argv){ 2097 2098 int tcp_flag = 0; 2099 struct option long_options[] = { 2100 { "tcp", no_argument, &tcp_flag, 1 }, 2101 { "help", no_argument, 0, 0 }, 2102 { 0,0,0,0 } // This is a filler for -1 2103 }; 2104 2105 while (1) { 2106 int c; 2107 int option_index = -1; 2108 c = getopt_long(argc, argv, "h", long_options, &option_index); 2109 if (c == -1) break; // no more option 2110 2111 // treat long parameter first 2112 if (option_index == -1) { 2113 switch (c) { 2114 case '?': 2115 case 'h': 2116 usage(argv[0]); 2117 return 0; 2118 break; 2119 } 2120 } else { 2121 switch (option_index) { 2122 case 1: 2123 usage(argv[0]); 2124 return 0; 2125 break; 2126 } 2127 } 2128 } 2129 2130 #ifndef HAVE_UNIX_SOCKETS 2131 // TCP is default if there are no unix sockets 2132 tcp_flag = 1; 2133 #endif 2134 2135 btstack_server_run(tcp_flag); 2136 } 2137 2138 void btstack_server_set_storage_path(const char * path){ 2139 if (btstack_server_storage_path){ 2140 free((void*)btstack_server_storage_path); 2141 btstack_server_storage_path = NULL; 2142 } 2143 btstack_server_storage_path = strdup(path); 2144 log_info("Storage path %s", btstack_server_storage_path); 2145 } 2146