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