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