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